Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to identify an inherited method in Python?

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?

like image 783
Danilo Bargen Avatar asked Oct 13 '11 09:10

Danilo Bargen


2 Answers

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'
like image 170
madjar Avatar answered Nov 02 '22 22:11

madjar


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).

like image 23
hamstergene Avatar answered Nov 02 '22 23:11

hamstergene