Get a method instance through 'getattr' but not superclass's method
Steve Holden
steve at holdenweb.com
Thu Mar 11 07:42:29 EST 2010
Radhakrishna Bhat wrote:
> I am using getattr to get a method instance from a class. But it also
> returns methods from the superclass. How to detect if an attribute is
> from superclass?
>
You could try, if x is in instance, looking to see whether the name is
defined in x.__class__.__dict__.
>>> class A:
... def method1(self):
... print "A1"
... def method2(self):
... print "A2"
...
>>> class B(A):
... def method2(self):
... print"B2"
... def method3(self):
... print "B3"
...
>>> a = A()
>>> b = B()
>>> b.method2()
B2
>>> b.method1()
A1
>>> b.method3()
B3
>>> b.__class__.__dict__
{'__module__': '__main__', 'method2': <function method2 at 0x7ff1d6bc>,
'method3': <function method3 at 0x7ff1d3ac>, '__doc__': None}
>>> a.__class__.__dict__
{'__module__': '__main__', 'method2': <function method2 at 0x7ff1d064>,
'__doc__': None, 'method1': <function method1 at 0x7ff1d6f4>}
>>>
I'd be interested to know why this is so important.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list