python - 获取子类的重写函数
reflection overriding (3)
只是为了详细说明,当您定义任何属性时,都会将任何属性添加到
Class
__dict__
属性中:
class A:
def a1(self):
pass
print('a1' in A.__dict__) # True Note: vars(A) == A.__dict__
并使用
built-in
callable
女巫检查属性是否为方法
built-in
如果对象
callable
(函数,方法,类等),则返回
True
:
print(callable(A.__dict__['a1'])) # True
现在,即使
B
是
A
子类但未定义
a1
,该属性也不会添加到
B.__dict__
:
class B(A):
pass
print('a1' in B.__dict__) # False
因此,通过仅比较
__dict__
属性的值,您将覆盖巫婆方法,巫婆是
A.__dict__
和
B.__dict__
中存在的方法
override_method = [attr for attr in B.__dict__ if attr in A.__dict__ and callable(A.__dict__[attr])]
注意:
我可以用
vars(A)
代替
A.__dict__
来简化代码,但我想展示python为新的Python开发人员添加的特殊属性。
有没有办法在Python中获取子类的所有替代函数?
例:
class A:
def a1(self):
pass
def a2(self):
pass
class B(A):
def a2(self):
pass
def b1(self):
pass
在这里,我想获得类
B
对象(或类对象本身)的列表
["a2"]
,因为类
B
仅覆盖单个方法,即
a2
。
您可以使用
cls.__bases__
访问父类,使用
dir
查找父类的所有属性,并使用
vars
访问类本身的所有属性:
def get_overridden_methods(cls):
# collect all attributes inherited from parent classes
parent_attrs = set()
for base in cls.__bases__:
parent_attrs.update(dir(base))
# find all methods implemented in the class itself
methods = {name for name, thing in vars(cls).items() if callable(thing)}
# return the intersection of both
return parent_attrs.intersection(methods)
>>> get_overridden_methods(B)
{'a2'}
class A:
def a1(self):
pass
def a2(self):
pass
class B(A):
def a2(self):
super().a2()
pass
def b1(self):
pass
obj = B()
obj.a2() # ***first give the output of parent class then child class***