开发者

Access to class attributes of parent classes

开发者 https://www.devze.com 2023-01-23 11:51 出处:网络
I would like to know what is the best way to get all the attributes of a class when I don\'t know the name of them.

I would like to know what is the best way to get all the attributes of a class when I don't know the name of them.

Let's say I have:

#!/usr/bin/python2.4

class A(object):
    outerA = "foobar outerA"
    def __init__(self):
        self.innerA = "foobar innerA"

class B(A):
    outerB = "foobar outerB"
    def __init__(self):
        super(B, self).__init__()
        self.innerB = "foobar innerB"

if __name__ == '__main__':
    b = B()

Using hasattr/getattr to get the "outerA" class field of my b instance works fine:

>>> print hasattr(b, "outerA")
>>> True

>>> print str(getattr(b, "outerA"))
>>> foobar outerA

Ok, that's good.

But what if I don't exactly know that b has inherited a field called "outerA" but I still want to get it?

To access b's inne开发者_Go百科r fields, I usually use b.__dict__ . To get b.outerB, I can use b.__class__.__dict__ but that still doesn't show "outerA" among it fields:

>>> print "-------"
>>> for key, val in b.__class__.__dict__.iteritems():
...     print str(key) + " : " + str(val)
>>> print "-------\n"

Shows:

-------
__module__ : __main__
__doc__ : None
__init__ : <function __init__ at 0xb752aaac>
outerB : foobar outerB
-------

Where's my outerA?? :D

I am sure I can keep "climbing" the class hierarchy and get all the fields, but that doesn't seem like the greatest solution...

As there are hasattr(), getattr()... isn't there something like a listattr() that would give all the available attributes of an instance?

Thank you!


I think you're looking for dir() - it works just as well within code as in the shell.


Try dir(b). The resulting list includes inherited attributes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号