>>> 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/
> 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__)
--
Gabriel Genellina
> On Fri, Mar 12, 2010 at 12:15 AM, Gabriel Genellina
> <gags...@yahoo.com.ar>wrote:
En Sat, 03 Apr 2010 13:37:45 -0300, Radhakrishna Bhat
<radhakr...@gmail.com> 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),
getattr(int,name,'*does*not*exist*'))
...
__module__: '__main__' '__builtin__'
bar: <unbound method MyClass.bar> '*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