프로그래밍/Python

C#으로 이해하는 Python - 클래스 (생성자, 소멸자)

QA Engineer - P군 2025. 1. 15. 01:33
반응형

처음 Python에서 클래스를 공부했을때 조금 다른 부분이 있어서 당황했는데 GPT 유료 결제 기념

나중에 참고 할 수 있게 C#으로 비교해보면서 다시 복습하는 시간을 가질 수 있게 되었다.

 

바로 본론 부터 하면 c#에서는 클래스 하나에서 생성하고 생성자와 소멸자를 설정하면 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
 
class MyClass
{
    public MyClass()
    {
        Console.WriteLine("Object is created.");
    }
 
    ~MyClass()
    {
        Console.WriteLine("Object is destroyed.");
    }
}
 
class Program
{
    static void Main()
    {
        using (MyClass obj = new MyClass())
        {
            Console.WriteLine("Using the object.");
        }        
    }
}
 
// --- 결과
// Object is created.
// Using the object.
// Object is disposed.
cs

 

그렇다면 파이썬에서는 생성자와 소멸자를 어떻게 사용할까?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyClass:
    def __new__(cls):
        print("Creating instance")
        return super().__new__(cls)
        
    def __del__(self):
        print("Object is destroyed.")
 
test = MyClass()
 
del test
 
# --- 결과
# Creating instance
# Initializing instance
cs

 

생성자는 _new_ 을 사용하고, 소멸자는 __del__을 사용하면 된다.

__init__ 도 있지만 초기화에 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyClass:
    def __new__(cls):
        print("Creating instance")
        return super().__new__(cls)
 
    def __init__(self):
        print("Initializing instance")
        
    def __del__(self):
        print("Object is destroyed.")
 
test = MyClass()
 
del test
 
# -- 
# Creating instance
# Initializing instance
# Object is destroyed.
cs

 

초기화 할 때는 __init__ 을 사용하자.

 

반응형