__del__ 메서드 구현 및 테스트
이 단계에서는 __del__ 메서드에 대해 배웁니다. 이 메서드는 최종자 (finalizer) 또는 소멸자 (destructor) 라고 불립니다. 객체의 참조 횟수 (reference count) 가 0 이 되어 파이썬의 가비지 컬렉터 (garbage collector) 에 의해 소멸될 예정일 때 호출됩니다. 네트워크 연결이나 파일 핸들 (file handle) 을 닫는 것과 같은 정리 작업에 자주 사용됩니다.
del 문을 사용하여 객체에 대한 참조를 제거할 수 있습니다. 마지막 참조가 사라지면 __del__이 자동으로 호출됩니다.
객체가 언제 소멸되는지 확인하기 위해 Dog 클래스에 __del__ 메서드를 추가해 보겠습니다.
dog_cat.py 파일을 다시 엽니다. 파일의 전체 내용을 다음 코드로 교체합니다. 이 버전은 (모듈 임포트 시 객체 생성을 피하기 위해) Dog 인스턴스를 생성하는 코드를 제거하고, Dog 클래스에 __del__ 메서드를 추가합니다.
## File Name: dog_cat.py
class Animal:
def __init__(self, name):
self._name = name
def say(self):
print(self._name + ' is saying something')
class Dog(Animal):
def __new__(cls, name, age):
instance = super().__new__(cls)
return instance
def __init__(self, name, age):
super().__init__(name)
self.age = age
def say(self):
print(self._name + ' is making a sound: wang wang wang...')
## 이 메서드를 Dog 클래스에 추가합니다
def __del__(self):
print(f'The Dog object {self._name} is being deleted.')
dog_cat.py 파일을 저장합니다.
이제 이 동작을 테스트하기 위한 별도의 스크립트를 작성해 보겠습니다. 파일 탐색기에서 test_del.py 파일을 엽니다.
test_del.py에 다음 코드를 추가합니다. 이 스크립트는 두 개의 Dog 인스턴스를 생성한 다음 그중 하나를 명시적으로 삭제합니다.
## File Name: test_del.py
from dog_cat import Dog
import time
print("Creating two Dog objects: d1 and d2.")
d1 = Dog('Tom', 3)
d2 = Dog('John', 5)
print("\nDeleting reference to d1...")
del d1
print("Reference to d1 deleted.")
## 가비지 컬렉터가 즉시 실행되지 않을 수 있습니다.
## 실행 시간을 주기 위해 약간의 지연을 추가합니다.
time.sleep(1)
print("\nScript is about to end. d2 will be deleted automatically.")
파일을 저장합니다. 이제 터미널에서 test_del.py 스크립트를 실행합니다.
python ~/project/test_del.py
출력을 관찰합니다. Tom에 대한 __del__ 메시지는 del d1이 호출된 후에 나타납니다. John에 대한 메시지는 스크립트가 종료될 때 d2 객체가 가비지 컬렉션되므로 맨 끝에 나타납니다.
Creating two Dog objects: d1 and d2.
Deleting reference to d1...
The Dog object Tom is being deleted.
Reference to d1 deleted.
Script is about to end. d2 will be deleted automatically.
The Dog object John is being deleted.
참고: 가비지 컬렉션의 정확한 타이밍은 다를 수 있습니다. __del__은 del이 사용된 직후가 아니라 객체가 수집될 때 호출됩니다.