我有一个类是许多其他类的父类(super class)。我想知道(在我的父类(super class)的 __init__()
中)子类是否覆盖了特定方法。
我试图用一个类方法来完成这个,但是结果是错误的:
class Super:
def __init__(self):
if self.method == Super.method:
print 'same'
else:
print 'different'
@classmethod
def method(cls):
pass
class Sub1(Super):
def method(self):
print 'hi'
class Sub2(Super):
pass
Super() # should be same
Sub1() # should be different
Sub2() # should be same
>>> same
>>> different
>>> different
有没有办法让父类(super class)知道子类是否覆盖了方法?
最佳答案
如果你想在 Python 3 中检查一个被覆盖的实例方法,你可以使用 self 的类型来做到这一点:
class Base:
def __init__(self):
if type(self).method == Base.method:
print('same')
else:
print('different')
def method(self):
print('Hello from Base')
class Sub1(Base):
def method(self):
print('Hello from Sub1')
class Sub2(Base):
pass
现在 Base() 和 Sub2() 应该都打印“相同”,而 Sub1() 打印“不同”。 classmethod 装饰器使第一个参数绑定(bind)到 self 的类型,并且由于子类的类型在定义上与其基类不同,因此两个类方法将比较为不相等。通过使方法成为实例方法并使用 self 的类型,您将一个普通函数与另一个普通函数进行比较,并假设函数(如果您使用 Python 2,则在这种情况下为未绑定(bind)方法)比较等于它们自己(其中它们在 C Python 实现中执行),就会产生所需的行为。
关于python - 如何检测python子类中的方法重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9436681/