Can I find out (dynamically) where a method is defined?

Lie Lie.1296 at gmail.com
Mon Jun 9 12:12:25 EDT 2008


On Jun 9, 10:28 pm, allendow... at gmail.com wrote:
> Hi All.
>
> In a complex inheritance hierarchy, it is sometimes difficult to find
> where a
> method is defined.  I thought it might be possible to get this info
> from the
> method object itself, but it looks like maybe not.  Here is the test
> case I tried:
>
> class A(object):
>     def method():
>         pass
>
> class B(A):
>     pass
>
> a = A()
> b = B()
>
> print a.method
> print b.method
>
> Since B inherits method from A, I thought that printing b.method might
> tell
> me that the definition is in A, but no.  Here's the output:
>
> <bound method A.method of <__main__.A object at 0xb7d55e0c>>
> <bound method B.method of <__main__.B object at 0xb7d55e2c>>
>
> This in indistinguishable from the case where B overrides method.
>
> So, is there any way to inspect a method to see where (in what class)
> it
> is defined?

I don't know if there is other easier methods, but if you have access
to the source code, you can always add a print function.

class A(object):
    def method(self):
        print 'Entering A.method'
        ... The rest of the codes ...

class B(A):
    def method(self):
        print 'Entering B.method'
        ... The rest of the codes ...

class C(A):
    pass

If you don't have access to the source code, that means you shouldn't
need to worry about it.

A rather odd thing I just noticed is this:

class A(object):
    def method(self):
        pass

class B(A):
    def method(self):
        pass

class C(A):
    pass

print A.method == B.method ## False
print A.method == C.method ## True



More information about the Python-list mailing list