생성자와 소멸자 (Constructor/Deconstructor)
객체지향 (생성자와 소멸자 메서드)
- 생성자는 객체를 생성될 때 호출됨
- 첫 번째 인자는 ‘self’
class Weapon:
def __init__(self, weight, damage, color):
self.weight = weight
self.damage = damage
self.color = color
‘Weapon’ Class의 Object가 생성됐을 때, ‘self.weight’를 ‘weight’로, ‘self.damage’를 ‘damage’로, ‘self.color’를 ‘color’로 설정
heavymachinegun = Weapon(60, 5, "black")
‘Weapon’ Class의 ‘heavymachinegun’ Object의 ‘weight’, ‘damage’, ‘color’를 입력받은 값으로 설정
- 소멸자는 객체가 소멸될 때 호출됨
- 첫 번째 인자는 ‘self’
class Weapon:
def __init__(self, weight, damage, color):
self.weight = weight
self.damage = damage
self.color = color
def __del__(self):
print("Object deleted.")
‘Weapon’ Class의 Object가 소멸됐을 때, “Object deleted”를 출력
heavymachinegun = Weapon(60, 5, "black")
‘Weapon’ Class의 ‘heavymachinegun’ Object의 ‘weight’, ‘damage’, ‘color’를 입력받은 값으로 설정
print(heavymachinegun.damage)
‘heavymachinegun’ Object의 ‘damage’ 속성을 출력