我有一个班是许多其他班的超级班。我想知道(在我的超级类的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
超级类有没有办法知道一个子类是否重写了一个方法?
作为对答案https://stackoverflow.com/a/9437273/1258307的回复,由于我还没有足够的点数来评论它,除非您将
im_func
替换为__func__
,否则它在python 3.4下无法工作(而且很可能是更高版本),因为函数不再具有__func__
属性,而只具有绑定方法。编辑:这是原始问题的解决方案(它适用于2.7和3.4,我假设所有其他版本介于两者之间):
结果如下:
你可以用你自己的装潢师。但这是一个技巧,只适用于控制实现的类。
通过比较实例字典的公共子集和基类本身,这样做似乎是最简单和足够的,例如:
运行并给出:
相关问题 更多 >
编程相关推荐