2017-03-09 3 views
-1

파이썬에서는 클래스와 인스턴스 모두에서 미리 정의되지 않은 클래스 변수에 액세스 할 수 있습니다. 그러나 개체 인스턴스에서 미리 정의 된 클래스 변수 (예 : "이름")에 액세스 할 수 없습니다. 내가 뭘 놓치고 있니? 감사.Python : 미리 정의 된 클래스 변수 액세스

다음은 내가 작성한 테스트 프로그램입니다.

class Test: 
     ''' 
     This is a test class to understand why we can't access predefined class variables 
     like __name__, __module__ etc from an instance of the class while still able 
     to access the non-predefined class variables from instances 
     ''' 

     PI_VALUE = 3.14 #This is a non-predefined class variable 

     # the constructor of the class 
     def __init__(self, arg1): 
       self.value = arg1 

     def print_value(self): 
       print self.value 

an_object = Test("Hello") 

an_object.print_value() 
print Test.PI_VALUE    # print the class variable PI_VALUE from an instance of the class 
print an_object.PI_VALUE  # print the class variable PI_VALUE from the class 
print Test.__name__    # print pre-defined class variable __name__ from the class 
print an_object.__name__  #print the pre-defined class varible __name__ from an instance of the class 
+1

클래스와 달리 인스턴스에는 정의 된 이름이 없으므로 '__name__'이 (가) 없습니다. 마찬가지로 인스턴스는 모듈에 정의되어 있지 않으므로'__module__ '을 가지지 않습니다. 또한 인스턴스가 사전 정의 된 클래스 변수에 액세스 할 수 없다는 것은 사실이 아닙니다. 예를 들어'__doc__' 및'__weakref__'뿐만 아니라'__init __() '와 같은 메소드도 있습니다. – ekhumoro

+0

감사합니다. 귀하의 설명은 명확한 의미를 갖습니다. – RebornCodeLover

답변

2

정상입니다. 클래스의 인스턴스는 해당 클래스의 __dict__에서 속성 확인을 참조하고 모든 조상의 __dict__을 참조하지만 클래스의 모든 속성이 __dict__에서 온 것은 아닙니다. 특히

, Test__name__ 오히려 클래스의 __dict__보다, 클래스를 나타내는 C 구조체의 필드에서 개최되며, 속성은 type.__dict____name__descriptor을 통해 발견된다. Test의 인스턴스는 속성 조회를 위해 이것을 보지 않습니다.

+0

아. 그건 설명해. 감사합니다 @ user2357112 – RebornCodeLover

0

"이유"에 대한 답변이 없습니다. 그러나 여기에 __class__를 사용하여 접근 할 수 있습니다.

>>> class Foo(object): pass 
... 
>>> foo = Foo() 
>>> foo.__name__ 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'Foo' object has no attribute '__name__' 
>>> foo.__class__.__name__ 
'Foo' 
>>> 
+1

위의 답변은 @ekhumoro 및 user2357112에서 확인하십시오. 그들의 반응은 foo .__ class __.__ name__이 왜 작동하는지 설명합니다. – RebornCodeLover

관련 문제