생성자란 객체가 만들어질 때마다 호출되는 메서드이다. 추가 처리가 필요한 경우 생성자를 재정의해서 사용할 수 있다.
Python에서 생성자는 다른 언어(C++ 등)와 다르게 명확하지 않다. 인스턴스를 메모리에 할당하는 new 메서드와 인스턴스에 속성을 부여하는 init 메서드로 나눌 수 있다. 먼저 new 메서드에서는 모든 클래스의 부모 클래스인 Object 클래스의 객체(object)를 반환하여 메모리를 할당한다. 이후, init가 호출되어 속성을 부여하게 된다.
class A:
def __new__(cls):
print('new instance') # 인스턴스가 생성될 때 print문을 추가
return object.__new__(cls)
def __init__(self):
print('instance initialize')
self.name = 'A'
a = A()
# new instance
# instance initialize
생성자와 반대 개념으로 객체가 소멸될 때마다 호출되는 메서드로, 추가 처리가 필요한 경우 재정의할 수 있다.
Python에서 소멸자는 del 메서드이다.
class A:
def __new__(cls):
print('new instance') # 인스턴스가 생성될 때 print문을 추가
return object.__new__(cls)
def __init__(self):
print('instance initialize')
self.name = 'A'
def __del__(self):
print('delete instance')
a = A()
# new instance
# instance initialize
# delete instance