[Tutor] Is it possible to tell, from which class an method was inherited from

Corey Richardson kb1pkl at aim.com
Wed Jan 19 12:41:28 CET 2011


On 01/19/2011 03:55 AM, Jojo Mwebaze wrote:
> Is it possible to tell, from which class an method was inherited from.
> take an example below
> 
> |class A:
> 
>    def foo():
>      pass
> class B(A):
> 
>    def boo(A):
>      pass
> 
> class C(B):
>    def coo()
> 
>      pass
> class D(C):
> 
>    def doo()
>       pass  
> 
>>>> dir (D)
> 
> ['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo']
> 
> |
> 
> Is there any method to tell me form which classes boo, coo, foo where
> inherited from?
> 
> 	
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Try using the information here:
http://stackoverflow.com/questions/1938755/getting-the-superclasses-of-a-python-class

>From there, you can use the following (probably sub-prime):

def findRootParent(obj, method, prev=None):
    for parent in obj.__bases__:
        if hasattr(parent, method):
            findRootParent(parent, method, parent)
            print "I'm in %s, it has it" % obj.__name__
        else:
            print "%s first had %s" % (obj.__name__, method)

Here's a little test and some output:

class A(object):
    def test1():
        pass
    def test2():
        pass

class B(A):
    def test3():
        pass

class C(B):
    def test4():
        pass
findRootParent(C, "test1")

Output:
A first had test1
I'm in B, it has it
I'm in C, it has it

That's just me hacking together a solution. I don't know if its the best
or if one of the gurus on the list have a better one. It doesn't really
work if you have multiple inheritance:

class A(object):
    def test1(): pass

class B(object):
    def test2(): pass

class C(A, B): pass
findRootParent(C, "test1")
findRootParent(C, "test2")

Output:
A first had test1
I'm in C, it has it
C first had test1
C first had test2
B first had test2
I'm in C, it has it

Hope it helps,
~Corey


More information about the Tutor mailing list