获取类的属性

时间:2012-03-03 16:48:58

标签: python python-3.x

有没有通过类名和实例获取类属性的通用方法?

class A:
    def __init__(self):
        self.prop = 1

a = A()

for attr, value in a.__dict__.items():
    print(attr, value) # prop, 1

class A:
    def __init__(self):
        self.prop = 1

for attr, value in A.__dict__.items():
    print(attr, value) 
   #__dict__, __doc__, __init__, __module__, __weakref__

为什么最后一个示例返回dir attibutes结果不同的原因?

1 个答案:

答案 0 :(得分:1)

__dict__, __doc__, __module__, ...实际上存在于一个类中,即使您尚未创建它们。它们是“内置的”。

因此dir向您展示它们是正常的。

实例中的

__dict__属性存储实例属性。

class A:
    def __init__(self):
        self.prop = 1

a = A()
for attr, value in a.__dict__.items():
    print(attr, value)

这显示了实例属性。并且只有一个实例属性 - propself.prop = 1

for attr, value in A.__dict__.items():

这会获得类属性。 prop已添加到实例中,因此不在此处。

请参阅http://docs.python.org/library/stdtypes.html#special-attributes

要从对象获取所有属性,包括类属性,基类属性,请使用inspect.getmembers

相关问题