출처 : https://www.pythontutorial.net/python-oop/python-delete-property/
How to Delete a Property from an Object in Python
In this tutorial, you'll learn how to use the property() class to delete the property of an object.
www.pythontutorial.net
Python Delete Property
클래스의 property을 만들려면 @property 데코레이터를 사용합니다. 내부적으로 @property 데코레이터는 setter, getter 및 deleter의 세 가지 메서드가 있는 property 클래스를 사용합니다.
deleter를 사용하여 개체에서 속성을 삭제할 수 있습니다. deleter() 메서드는 클래스가 아닌 객체의 속성을 삭제합니다.
다음은 name 속성을 가진 Person 클래스를 정의합니다.
from pprint import pprint
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if value.strip() == '':
raise ValueError('name cannot be empty')
self._name = value
@name.deleter
def name(self):
del self._name
Person 클래스에서는 @name.deleter 데코레이터를 사용합니다. deleter 내에서 del 키워드를 사용하여 Person 인스턴스의 _name 속성을 삭제합니다.
다음은 Person 클래스의 __dict__ 보여 줍니다.
pprint(Person.__dict__)
Output:
mappingproxy({'__dict__': <attribute '__dict__' of 'Person' objects>,
'__doc__': None,
'__init__': <function Person.__init__ at 0x000001DC41D62670>,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'Person' objects>,
'name': <property object at 0x000001DC41C89130>})
Person.__dict__ 클래스에는 name 변수가 있습니다. 다음은 Person 클래스의 새 인스턴스를 만듭니다.
person = Person('John')
person.__dict__에는 _name 속성이 있습니다.
pprint(person.__dict__)
Output:
{'_name': 'John'}
다음은 del 키워드를 사용하여 name 속성을 삭제합니다.
del person.name
내부적으로 파이썬은 person 객체에서 _name 속성을 삭제하는 deleter 메서드를 실행합니다 . person.__dict__는 다음과 같이 비어 있습니다.
{}
name 속성에 다시 액세스하려고하면 오류가 발생합니다.
print(person.name)
Error:
AttributeError: 'Person' object has no attribute '_name'
Summary
- deleter 데코레이터를 사용하여 인스턴스의 속성을 삭제합니다.
'Python Object-oriented Programming' 카테고리의 다른 글
overriding-method (0) | 2023.04.04 |
---|---|
inheritance (0) | 2023.04.04 |
readonly-property (0) | 2023.04.04 |
properties (0) | 2023.04.04 |
__del__ Method (0) | 2023.04.04 |
댓글