출처 : https://www.pythontutorial.net/python-oop/python-class-variables/
Introduction to the Python class variables
클래스를 포함해서 파이썬의 모든 것은 객체입니다. 즉, 클래스는 파이썬의 객체입니다.
class 키워드를 사용하여 클래스를 정의하면 Python은 클래스 이름과 동일한 이름을 가진 객체를 만듭니다. 예를 들어:
class HtmlDocument:
pass
이 예제에서는 클래스와 개체를 정의합니다 . 객체에는 __name__ 속성이 있습니다.
print(HtmlDocument.__name__) # HtmlDocument
# instance 속성은 아니다.
그리고 HTMLDocument에서 보듯이 클래스의 type이 type입니다.
class HtmlDocument:
pass
h= HtmlDocument()
print(type(HtmlDocument)) # <class 'type'>
print(type(h)) # <class '__main__.HtmlDocument'>
# instance의 type은 type이 아니다.
또한 type 클래스의 인스턴스이기도합니다.
print(isinstance(HtmlDocument, type)) # True
클래스 변수는 클래스에 바인딩됩니다. 해당 클래스의 모든 인스턴스에서 공유됩니다.
다음 예제에서는 extension 및 version 클래스 변수를 HtmlDocument 클래스에 추가합니다. (class 변수로)
class HtmlDocument:
extension = 'html'
version = '5'
Get the values of class variables
class variables의 값을 얻기위해 , dot notation (.
)사용
print(HtmlDocument.extension) # html
print(HtmlDocument.version) # 5
존재하지 않는 클래스 변수에 액세스하면 AttributeError 예외가 발생합니다. 예를 들어:
HtmlDocument.media_type
Error:
AttributeError: type object 'HtmlDocument' has no attribute 'media_type'
클래스 변수의 값을 얻는 또 다른 방법은 getattr() 함수를 사용하는 것입니다 .
getattr() 함수는 객체와 변수 이름을 인수로 받아, 클래스 변수의 값을 반환합니다. 예를 들어:
extension = getattr(HtmlDocument, 'extension')
version = getattr(HtmlDocument, 'version')
print(extension) # html
print(version) # 5
클래스 변수가 없으면 AttributeError 예외도 발생합니다 . 예외를 방지하려면 다음과 같이 클래스 변수가 존재하지 않는 경우 기본값을 지정할 수 있습니다.
media_type = getattr(HtmlDocument, 'media_type', 'text/html')
print(media_type) # text/html
Set values for class variables
class variables의 값을 set 하기 위해 , dot notation ( . )사용
HtmlDocument.version = 10
또는 setattr() built-in function를 사용할 수 있습니다.
setattr(HtmlDocument, 'version', 10)
Python은 동적 언어이기 때문에 클래스 변수를 만든 후 런타임에 클래스에 클래스 변수를 추가할 수 있습니다. 예를 들어, 다음은 media_type 클래스 변수를 HtmlDocument 클래스에 추가합니다.
HtmlDocument.media_type = 'text/html'
print(HtmlDocument.media_type)
마찬가지로 setattr() 함수를 사용할 수 있습니다.
setattr(HtmlDocument, media_type, 'text/html')
print(HtmlDocument.media_type)
Delete class variables
런타임에 클래스 변수를 삭제하려면 delattr() 함수를 사용합니다.
delattr(HtmlDocument, 'version')
또는 del 키워드를 사용할 수 있습니다.
del HtmlDocument.version
Class variable storage
파이썬은 __dict__ 속성에 클래스 변수를 저장합니다. __dict__는 사전형식의 mapping proxy입니다. 예를 들어:
from pprint import pprint
class HtmlDocument:
extension = 'html'
version = '5'
HtmlDocument.media_type = 'text/html'
pprint(HtmlDocument.__dict__)
Output:
mappingproxy({'__dict__': <attribute '__dict__' of 'HtmlDocument' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'HtmlDocument' objects>,
'extension': 'html',
'media_type': 'text/html',
'version': '5'})
출력에서 명확하게 볼 수 있듯이 __dict__에는 미리 정의된 다른 클래스 변수 외에 extension, media_type 및 version의 세 가지 클래스 변수가 있습니다.
파이썬은 __dict__ 변수를 직접 변경하는 것을 허용하지 않습니다 .
예를 들어 다음과 같은 경우 오류가 발생하거나 오류가 발생합니다.
HtmlDocument.__dict__['released'] = 2008
Output:
TypeError: 'mappingproxy' object does not support item assignment
그러나 setattr() 함수 또는 dot notation을 사용하여 __dict__ 속성을 간접적으로 변경할 수 있습니다.
또한 __dict__에서 keys 의 type은 파이썬이 변수 조회 속도를 높이는데 도움이되는 문자열입니다.
Python은 __dict__ 사전을 통해 클래스 변수에 액세스할 수 있지만 좋은 방법은 아닙니다. 또한 일부 상황에서는 작동하지 않습니다. 예를 들어:
print(HtmlDocument.__dict__['type']) # BAD CODE
Callable class attributes
클래스 속성은 함수처럼 모든 개체가 될 수 있습니다.
클래스에 함수를 추가하면 함수는 클래스 속성이 됩니다. 함수는 호출 가능하므로 그 class 속성을 callable class attribute이라고 합니다. 예를 들면 다음과 같습니다.
from pprint import pprint
class HtmlDocument:
extension = 'html'
version = '5'
def render():
print('Rendering the Html doc...')
pprint(HtmlDocument.__dict__)
Output:
mappingproxy({'__dict__': <attribute '__dict__' of 'HtmlDocument' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'HtmlDocument' objects>,
'extension': 'html',
'render': <function HtmlDocument.render at 0x0000010710030310>,
'version': '5'})
이 예제에서 render은 HtmlDocument 클래스의 클래스 속성입니다. 그 값은 함수입니다.
Summary
- 클래스는 type 클래스의 인스턴스인 객체입니다.
- 클래스 변수는 클래스 객체의 속성입니다.
- dot notation또는 getattr() 함수를 사용하여 클래스 속성의 값을 get
- dot notation또는 setattr() 함수를 사용하여 클래스 속성의 값을 set
- 파이썬은 동적 언어입니다. 따라서 런타임에 클래스 변수를 클래스에 할당할 수 있습니다.
- 파이썬은 __dict__ 속성에 클래스 변수를 저장합니다 . __dict__ 속성은 사전입니다.
- 클래스에 바인딩된 함수는 callable class attribute이다.
( 클래스 속성은 함수처럼 모든 개체가 될 수 있습니다. )
'Python Object-oriented Programming' 카테고리의 다른 글
Class Methods (0) | 2023.04.02 |
---|---|
Methods (0) | 2023.04.02 |
Class attributes (0) | 2023.04.02 |
Class (0) | 2023.04.02 |
Callable (0) | 2023.04.02 |
댓글