Constructor
Constructor
μμ±μ (Constructor)
κ°μ²΄λ₯Ό μμ±ν λ νΈμΆλλ ν¨μλ‘μ, κ°μ²΄ μμ±μ μ΄κΈ°ν μμ μ μν΄ μ‘΄μ¬
class ν΄λμ€λͺ
:
def __init__(self):
λ¬Έμ₯
λ€μκ³Ό κ°μ΄ initλΌλ μ΄λ¦μΌλ‘ 미리 μ μλλ©°, μμ±μλ₯Ό ν΅ν΄μ κ°μ²΄κ° μμ±λ λ μ΄λ€ λ³μμ κ°μ μΈν νλ λ± μ¬λ¬κ°μ§ μμ μ ν μ μλ€
class example:
def __init__(self, sentence):
self.name = sentence
print("κ°μ²΄κ° μμ±: " + sentence + "μ
λλ€.")
object= example("μ¬κ³Ό") # κ°μ²΄κ° μμ±: μ¬κ³Όμ
λλ€.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduction(self):
print("μ μ΄λ¦μ " + self.name + "μ΄λ©°, μ λμ΄λ " + str(self.age) + "μ΄μ
λλ€.")
objectStudent = Student("μλΉ", 28)
objectStudent.introduction() # μ μ΄λ¦μ μλΉμ΄λ©°, μ λμ΄λ 28μ΄μ
λλ€.
μλ©Έμ (Destructor)
μμ±μμ λ°λλ‘ κ°μ²΄κ° μλ©Έν λ νΈμΆλλ μλ©Έμκ° μλ€
delμΌλ‘ μ μ λμ΄ μμΌλ©°, 리μμ€ ν΄μ²΄ λ±μ μ’ λ£ μμ μ νκΈ° μν΄ μ¬μ©
class ν΄λμ€λͺ
:
def __del__(self):
λ¬Έμ₯
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
print("κ°μ²΄ μμ± : μ μ΄λ¦μ " + self.name + "μ΄λ©°, μ λμ΄λ " + str(self.age) + "μ΄μ
λλ€.")
def __del__(self):
print("κ°μ²΄ μλ©Έ")
objectStudent = Student("μλΉ", 28)
# κ°μ²΄ μμ± : μ μ΄λ¦μ μλΉμ΄λ©°, μ λμ΄λ 28μ΄μ
λλ€.
print(objectStudent) # <__main__.Student object at 0x0000029D72681F48>
del objectStudent
# κ°μ²΄ μλ©Έ
# print(objectStudent) # name 'objectStudent' is not defined
Last updated
Was this helpful?