파이썬 객체의 생명주기

매일 공부(ML)·2022년 3월 3일
0

생성자(Constructor)와 소멸자(Destructor)

파이썬의 생성자는 init, 소멸자는 del로 정의합니다.

이 코드에서는 객체를 생성할 때 생성자가 실행이 되고, 객체가 사라질 때 소멸자가 실행되는 것을 볼 수 있습니다.

class PartyAnimal:
    x = 0

    def __init__(self):
        print('I am constructed')

    def party(self) :
        self.x = self.x + 1
        print('So far',self.x)

    def __del__(self):
        print('I am destructed', self.x)

an = PartyAnimal()
an.party()
an.party()
an = 42
print('an contains',an)

# I am constructed
# So far 1
# So far 2
# I am destructed 2
# an contains 42

이 코드에서는 객체를 생성할 때 이름을 매개 변수로 넣어 name이라는 속성에 저장을 합니다.


class PartyAnimal:
    x = 0
    name = ""
    def __init__(self, z):
        self.name = z
        print(self.name,"constructed")

    def party(self) :
        self.x = self.x + 1
        print(self.name,"party count",self.x)

s = PartyAnimal("Sally")
j = PartyAnimal("Jim")

s.party()
j.party()
s.party()

# Sally constructed
# Jim constructed
# Sally party count 1
# Jim party count 1
# Sally party count 2

이 코드의 결과를 보면 객체를 두 번 생성할 경우 name이라는 속성과 x라는 속성은 각각 별개의 값을 저장한다는 걸 알 수 있습니다.

profile
성장을 도울 아카이빙 블로그

0개의 댓글