那么是否可以获得最具体的类的字典/属性列表?到目前为止我正在使用
for attr, value in obj.__class__.__dict__.iteritems():
但这也会给我超级中定义的属性。有什么方法可以避免这种情况吗?
答案 0 :(得分:3)
类具有由字典对象实现的命名空间。类 属性引用被转换为此字典中的查找, 例如,C.x被翻译为C .__ dict __ [“x”](虽然对于新式 特别是类有许多允许的钩子 其他定位属性的方法)。当属性名称不是 在那里找到,属性搜索在基类
中继续
换句话说,__ dict__只包含类的“本地”属性,超类的属性存储在超类__dict __中。
因此,您可以使用__class__.__dict__.iteritems()
仅检索类属性。
答案 1 :(得分:1)
它没有显示超类的属性:
>>> class A(object):
def a(self):
print a
b = 3
>>> a = A()
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
>>> list(a.__class__.__dict__)
['a', '__module__', 'b', '__dict__', '__weakref__', '__doc__']
__module__
,__dict__
,__weakref__
,__doc__
似乎是默认为每个类创建的属性。
此旧样式类的默认属性列表不同:
>>> class B:
pass
>>> list(B().__class__.__dict__)
['__module__', '__doc__']