2007. 7. 11. 20:37
Code/Python
이강성 <파이썬> 379p - 생성자와 소멸자
실행하면
test 함수가 불리면서 Life 클래스 인스턴스가 하나 생성된다. 이때 자동으로 __init__ 함수가 호출되어 Birthday를 츨력한다. 3초 후에 test 함수가 종료하면서 (mylife는 지역 이름이므로 함수가 종료되면서 사라진다.) 인스턴스가 소멸된다. 이때 자동으로 __del__ 함수가 호출된다.
from time import time, ctime, sleep
class Life:
def __init__(self):
self.birth = ctime()
print 'Birthday', self.birth
def __del__(self):
print 'Deathday', ctime()
def test():
mylife = Life()
print 'Sleepling for 3 sec'
sleep(3)
test()
class Life:
def __init__(self):
self.birth = ctime()
print 'Birthday', self.birth
def __del__(self):
print 'Deathday', ctime()
def test():
mylife = Life()
print 'Sleepling for 3 sec'
sleep(3)
test()
실행하면
Birthday Wed Jul 11 20:29:36 2007
Sleepling for 3 sec
Deathday Wed Jul 11 20:29:39 2007
Sleepling for 3 sec
Deathday Wed Jul 11 20:29:39 2007
test 함수가 불리면서 Life 클래스 인스턴스가 하나 생성된다. 이때 자동으로 __init__ 함수가 호출되어 Birthday를 츨력한다. 3초 후에 test 함수가 종료하면서 (mylife는 지역 이름이므로 함수가 종료되면서 사라진다.) 인스턴스가 소멸된다. 이때 자동으로 __del__ 함수가 호출된다.
'Code > Python' 카테고리의 다른 글
2차원 행렬 테스트 (0) | 2007.08.03 |
---|---|
Lists (0) | 2007.08.01 |