강의

멘토링

커뮤니티

Inflearn Community Q&A

tnsdud35060196's profile image
tnsdud35060196

asked

Python 100 Problem Solving with Examples Part 3

Instance, Object, Object Count

소멸자 관련 질문

Written on

·

246

1

안녕하세요.

소멸자는 인스턴스 객체를 생성한 후에 소멸시에 사용하는 것으로 알고 있습니다.

인스턴스 객체 p1만 소멸 시키고자 del p1을 수행했는데 p2까지 모두 소멸되었습니다.

소멸자는 객체 소멸이아니라 클래스 전체를 소멸하는 것인지 알고 싶습니다.

소멸자를 사용하는 이유가 메모리 효율때문인것같은데 어느 타이밍에 사용해야 하는지도 알고 싶습니다.

 

코드

import random


class Person:

    # 클래스 변수
    count_class_var = 0

    # 생성자
    def __init__(self, name, age, power):
        self.name = name
        self.age = age
        self.power = power
        self.increase_obj()

    # 클래스 메서드
    def increase_obj(self):
        Person.count_class_var += 1

    # 소멸자
    def __del__(self):
        print(self.name + ' 소멸되었습니다.')
        Person.count_class_var -= 1


def add_power_level():
    return random.choice([i for i in range(1, 11)])


# [2]:클래스 사용
p1 = Person('홍길동', 20, add_power_level())
print(Person.count_class_var)

p2 = Person('강감찬', 30, 9)
print(Person.count_class_var)

del p1

 

결과

1
2
홍길동 소멸되었습니다.
강감찬 소멸되었습니다.
python

Answer 1

0

저도 똑같은 질문이 있습니다

저는 심지어 del 명령을 실행하지도 않았는데

생성된 객체들이 모두 없어질 때까지 자동으로 소멸자가 작동되었습니다

혹시 질문에 대한 해답을 얻으셨나요?

tnsdud35060196's profile image
tnsdud35060196

asked

Ask a question