如何检测python子类中的方法重载? [英] How to detect method overloading in subclasses in python?
本文介绍了如何检测python子类中的方法重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类是许多其他类的超类.我想知道(在我的超类的 __init__()
中)子类是否覆盖了特定的方法.
I have a class that is a super-class to many other classes. I would like to know (in the __init__()
of my super-class) if the subclass has overridden a specific method.
我试图用一个类方法来完成这个,但结果是错误的:
I tried to accomplish this with a class method, but the results were wrong:
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
有没有办法让超类知道子类是否覆盖了一个方法?
Is there any way for a super-class to know if a sub-class has overridden a method?
推荐答案
您可以使用自己的装饰器.但这是一个技巧,仅适用于您控制实现的类.
You can use your own decorator. But this is a trick and will only work on classes where you control the implementation.
def override(method):
method.is_overridden = True
return method
class Super:
def __init__(self):
if hasattr(self.method, 'is_overridden'):
print 'different'
else:
print 'same'
@classmethod
def method(cls):
pass
class Sub1(Super):
@override
def method(self):
print 'hi'
class Sub2(Super):
pass
Super() # should be same
Sub1() # should be different
Sub2() # should be same
>>> same
>>> different
>>> same
这篇关于如何检测python子类中的方法重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文