programing

Python에서 클래스 변수를 정의하는 올바른 방법

kingscode 2022. 10. 30. 20:41
반응형

Python에서 클래스 변수를 정의하는 올바른 방법

Python에서는 클래스 속성을 두 가지 방법으로 초기화합니다.

첫 번째 방법은 다음과 같습니다.

class MyClass:
  __element1 = 123
  __element2 = "this is Africa"

  def __init__(self):
    #pass or something else

다른 스타일은 다음과 같습니다.

class MyClass:
  def __init__(self):
    self.__element1 = 123
    self.__element2 = "this is Africa"

클래스 속성을 초기화하는 올바른 방법은 무엇입니까?

어느 쪽이든 정확하거나 부정확할 필요는 없습니다.그것은 단지 다른 두 종류의 클래스 요소일 뿐입니다.

  • 외부 요소__init__method는 정적 요소이며 클래스에 속합니다.
  • 내부 요소__init__method는 객체의 요소입니다(self클래스에 속하지 않습니다.

몇 가지 코드를 사용하면 더 명확하게 알 수 있습니다.

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

보시다시피 클래스 요소를 변경하면 두 객체 모두 변경됩니다.그러나 오브젝트 요소를 변경해도 다른 오브젝트는 변경되지 않았습니다.

이 샘플은 스타일의 차이를 설명해 주는 것 같습니다.

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1은 클래스에 바인딩되고 element2는 클래스의 인스턴스에 바인딩됩니다.

언급URL : https://stackoverflow.com/questions/9056957/correct-way-to-define-class-variables-in-python

반응형