파이썬에서는 클래스와 인스턴스 모두에서 미리 정의되지 않은 클래스 변수에 액세스 할 수 있습니다. 그러나 개체 인스턴스에서 미리 정의 된 클래스 변수 (예 : "이름")에 액세스 할 수 없습니다. 내가 뭘 놓치고 있니? 감사.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
클래스와 달리 인스턴스에는 정의 된 이름이 없으므로 '__name__'이 (가) 없습니다. 마찬가지로 인스턴스는 모듈에 정의되어 있지 않으므로'__module__ '을 가지지 않습니다. 또한 인스턴스가 사전 정의 된 클래스 변수에 액세스 할 수 없다는 것은 사실이 아닙니다. 예를 들어'__doc__' 및'__weakref__'뿐만 아니라'__init __() '와 같은 메소드도 있습니다. – ekhumoro
감사합니다. 귀하의 설명은 명확한 의미를 갖습니다. – RebornCodeLover