开发者

retrieving the keys of all variables on an object

If I had:

class A(object):
    varA = 1

inst = A()

Then how would I retrieve the keys of all variables on inst? I'd want something like ["varA"]

So far, I've gotten this:

vars(inst.__class__).keys() #returns ['__dict__', '__weakref__', '开发者_如何学Go__module__', 'varA', '__doc__']

I'm fine with that, I'd just ignore the double-under vars. My problem is with multiple layers of inheritance like:

class A(object):
    varA = 1

class B(A):
    varB = 2

inst = B()
vars(inst.__class__).keys() #returns ['__module__', '__doc__', 'varB']

but I want to retrieve both varB and varA. Any idea how I would go about doing this?

I also tried:

vars(super(B, inst).__class__).keys()+vars(inst.__class__).keys()

But that didn't do what I expected.

If it matters, I'm using Python 2.6.

Edit: I actually just stumbled across a very easy way to do this: dir(inst)


There is a python module, called inspect for runtime introspection. Maybe inspect.getmembers can help you ...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜