2012-03-03 7 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

을 사용 http://docs.python.org/library/stdtypes.html#special-attributes

객체에서 얻을하는 방법을 참조하십시오? – grifaton

+0

> 클래스 이름 및 인스턴스별로 클래스의 속성을 가져 오는 보편적 인 방법이 있습니까? <나는 이것을 이해하지 못했다 – warvariuc

+0

두 번째 예제에서 클래스 속성을 얻는 방법을 의미한다 (나는'prop, 1'을 얻고 싶다)? – Opsa

답변

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) 

이것은 인스턴스 속성을 보여줍니다. 그리고 거기에 하나의 인스턴스 속성입니다 - prop (self.prop = 1)

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

는 그리고 이것은 클래스 속성을 가져옵니다. prop이 인스턴스에 추가되었으므로 여기에 없습니다.

클래스 속성, 기본 클래스의 속성을 포함한 모든 속성이, 당신이 당신을 제공하기 위해 무엇을 기대 inspect.getmembers

+0

Thx를 읽으십시오.하지만 인스턴스별로 'class' 속성을 얻는 방법을 알려주십시오. – Opsa