Code/Python

생성자와 소멸자

maetel 2007. 7. 11. 20:37
이강성 <파이썬> 379p - 생성자와 소멸자

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()

실행하면
Birthday Wed Jul 11 20:29:36 2007
Sleepling for 3 sec
Deathday Wed Jul 11 20:29:39 2007


test 함수가 불리면서 Life 클래스 인스턴스가 하나 생성된다. 이때 자동으로 __init__ 함수가 호출되어 Birthday를 츨력한다. 3초 후에 test 함수가 종료하면서 (mylife는 지역 이름이므로 함수가 종료되면서 사라진다.) 인스턴스가 소멸된다. 이때 자동으로 __del__ 함수가 호출된다.