I want to tell inherited methods apart from overloaded or newly defined methods. Is that possible with Python?
Example:
class A(object):
def spam(self):
print 'A spam'
def ham(self):
print 'A ham'
class B(A):
def spam(self):
print 'Overloaded spam'
def eggs(self):
print 'Newly defined eggs'
Desired functionality:
>>> magicmethod(B.spam)
'overloaded'
>>> magicmethod(B.ham)
'inherited'
>>> magicmethod(B.eggs)
'newly defined'
Is there a "magic method" like in the example, or some way to tell those types of method implementations apart?
I'm not sure it's a good idea, but you can probably do it by using hasattr
and __dict__
.
def magicmethod(clazz, method):
if method not in clazz.__dict__: # Not defined in clazz : inherited
return 'inherited'
elif hasattr(super(clazz), method): # Present in parent : overloaded
return 'overloaded'
else: # Not present in parent : newly defined
return 'newly defined'
If you know the ancestor, you can simply test:
>>> B.spam == A.spam
False
>>> B.ham == A.ham
True
And to find list of all base classes, look here: List all base classes in a hierarchy of given class?
I shall also point that if you need this, your class design is probably wrong. You should not care about such things in OOP (unless you're creating an object inspector or something like that).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With