Get a method instance through 'getattr' but not superclass's method

Radhakrishna Bhat radhakrishna12 at gmail.com
Thu Mar 11 08:15:19 EST 2010


Thanks. I just have to check in that string if method1 is from present in
subclass's __dict__ or not.
This is important for me because in my code, I am dynamically calling
methods of 2 classes where one is superclass of the other. And I was getting
duplicate results because of this problem.

-Radhakrishna

On Thu, Mar 11, 2010 at 6:12 PM, Steve Holden <steve at holdenweb.com> wrote:

> 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/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100311/82e62b7e/attachment-0001.html>


More information about the Python-list mailing list