2012-03-03 84 views
0

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

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为何结果不同?

+0

,你会看到什么给你? – grifaton 2012-03-03 16:53:00

+0

>有没有通过类名和实例获取类的属性的通用方法? <我不明白这个 – warvariuc 2012-03-03 16:57:24

+0

我的意思是如何获得第二个例子中的类属性(我想获得'prop,1')? – Opsa 2012-03-03 17:01:20

回答

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

+0

Thx为您的答案,但告诉如何通过实例获得'class'属性? – Opsa 2012-03-03 16:58:24