在父母中找出覆盖方法
我熟悉OOP,并了解我们可以从基类继承并扩展 user_call_api 在子类中添加更多定义。但是我想知道是否有一种方法是在父班中,我们可以找出
- 哪些方法被覆盖了(子类)
- 的名称(儿童)类的名称已覆盖该方法
class Parent:
def call_api(self):
print("API is called")
def use_call_api(self):
# if it's overridden, find out in parent,
# do something and then
self.call_api()
# if it's not overridden
self.call_api()
class Child(Parent):
def call_api(self):
print("call_api")
class Child2(Parent):
def call_api(self):
print("call_api2")
class Child3(Parent):
def call_api(self):
print("call_ap3")
def use_call_api(self):
print("custom call_api")
I am familiar with OOP, and understand we can inherit from a base class and extend user_call_api in a child class adding more definitions to it. But I'm wondering is there a way that in parent class, we could find out
- which methods are overridden (by child classes)
- the name of (child) classes that have overridden the method
class Parent:
def call_api(self):
print("API is called")
def use_call_api(self):
# if it's overridden, find out in parent,
# do something and then
self.call_api()
# if it's not overridden
self.call_api()
class Child(Parent):
def call_api(self):
print("call_api")
class Child2(Parent):
def call_api(self):
print("call_api2")
class Child3(Parent):
def call_api(self):
print("call_ap3")
def use_call_api(self):
print("custom call_api")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以拥有一个元素,该元素将覆盖
__新的__
dunder-hodod,并将必要的信息(方法名称和类名称覆盖它覆盖的方法和类名称)置于其singleton属性中。这些类(主要是从
parent
继承的子类)应使用Inspect
metaclass。Inspect.implementations
将在应用程序启动后处于最终状态,并且在动态内存中声明所有类和功能以准备执行脚本。因此,您可以在parent
中获得声明的其他方法,以获取覆盖当前方法的类列表,甚至是覆盖方法是否覆盖的方法。如果运行上述代码,则您会看到,当
child
覆盖use_call_api
方法时,覆盖>覆盖
通过相同方法调用的方法parent
将包含child
,表明它覆盖了该方法。如果我们不实现use_call_api
condy
,则覆盖>覆盖
将返回一个空元组,而如果self.overridden()
代码>条件将行不通,并且会通过案例。You can have a metaclass that will override the
__new__
dunder-method and hold the necessary information (method name and class names that overrides it) into the singleton property of it.The classes (primarily the child classes inherited from
Parent
) should useInspect
metaclass.The
Inspect.implementations
will be in their final state after the application starts and all classes and functions are declared in dynamic memory to be ready to execute the script. So you can get declare an additional method in theParent
to get the list of classes that override the current method or even was the method overridden or not.If you run the above code, then you will see that when
Child
overridesuse_call_api
method, then theoverridden
method called by the same method of theParent
will contain theChild
, indicating that it overrides the method. If we do not implementuse_call_api
forChild
, theoverridden
would return an empty tuple, andif self.overridden()
condition would not work and will pass the case.