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

Gabriel Genellina gagsl-py2 at
Sun Apr 4 00:58:01 CEST 2010

Please reply inline; top posting is harder to read.

> On Fri, Mar 12, 2010 at 12:15 AM, Gabriel Genellina
> <gagsl-py2 at>wrote:
>> En Thu, 11 Mar 2010 01:47:30 -0300, Radhakrishna Bhat
>> <radhakrishna12 at> escribió:
>>  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 may look it up directly in the class dictionary (__dict__)

En Sat, 03 Apr 2010 13:37:45 -0300, Radhakrishna Bhat  
<radhakrishna12 at> escribió:>

> thanks. It is working for simple classes. But now i am trying for complex
> objects.
> myclassinstance.__class__.dict__ returns <dictproxy object at %$^%>
> Looping through the same returned dictproxy gives attributes of  
> superclass.
> What am i doing wrong?

Could you provide a failing example?
It works for me in this case:

py> class MyClass(int):
...   "This is my derived class"
...   foo = 1
...   def bar(self): pass
py> MyClass
<class '__main__.MyClass'>
py> MyClass.__dict__
<dictproxy object at 0x00C158F0>
py> MyClass.__dict__.keys()
['__module__', 'bar', '__dict__', 'foo', '__weakref__', '__doc__']
py> for name in MyClass.__dict__:
...   print '%s: %.30r %.30r' % (name, getattr(MyClass,name),  
__module__: '__main__' '__builtin__'
bar: <unbound method> '*does*not*exist*'
__dict__: <dictproxy object at 0x00C15E7 <dictproxy object at 0x00C158F
foo: 1 '*does*not*exist*'
__weakref__: <attribute '__weakref__' of 'M '*does*not*exist*'
__doc__: 'This is my derived class' 'int(x[, base]) -> integer\n\n

foo and bar are new attributes. __module__, __dict__, __weakref__ and  
__doc__ are different from the base class.
If you want to filter out the last four:

- ignore all attribute names starting and ending with two underscores:
   if name[:2] == '__' == name[-2:]: continue

- ignore all attributes already present in the base class.
   if hasattr(int, name): continue

Gabriel Genellina

More information about the Python-list mailing list