如何检测方法重载在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.
但是结果是错误的:
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屋!
查看全文