[파이썬] 생성자와 소멸자(init, del)

Python is an object-oriented programming language that allows the creation of classes and objects. In Python, classes can have special methods called constructors and destructors. Constructors are used to initialize class objects, while destructors are used to clean up resources when the object is no longer in use.

생성자 (Init)

A constructor is a special method in a class that is invoked when a new object is created. In Python, the constructor method is called __init__(), and it is automatically invoked when an object is instantiated.

The __init__() method can be used to set up the initial state of an object by initializing its instance variables or performing any other setup required for the object to function properly.

Here is an example of a simple class with a constructor:

class MyClass:
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

# Creating an instance of MyClass
obj = MyClass("Hello", 10)

print(obj.param1)  # Output: Hello
print(obj.param2)  # Output: 10

In the above example, we define a class called MyClass with a constructor that takes two parameters param1 and param2. When we create an object obj of the MyClass class, the __init__() method is automatically called and initializes the instance variables param1 and param2.

소멸자 (Del)

A destructor is another special method in a class that is called when an object is about to be destroyed or garbage collected. In Python, the destructor method is called __del__().

The destructor is useful for releasing resources or performing cleanup operations before an object is destroyed.

Here is an example of a class with a destructor:

class MyClass:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f"Object {self.name} is being destroyed!")

# Creating an object of MyClass
obj = MyClass("MyObject")

# Performing some operations

# Deleting the object
del obj  # Output: Object MyObject is being destroyed!

In the above example, we define a class called MyClass with a constructor and a destructor. When we create an object of MyClass and then delete it using the del keyword, the destructor __del__() is automatically called and performs the cleanup operation.

It’s important to note that the destructors are not guaranteed to be called immediately when the object goes out of scope. Python uses a garbage collector that runs periodically to automatically free up memory.

Conclusion

Constructors and destructors are important methods in Python classes that allow us to initialize objects and perform cleanup operations, respectively. The constructor __init__() initializes an object’s state, while the destructor __del__() is called when the object is about to be destroyed. Understanding how to use constructors and destructors is essential for proper object initialization and resource management in Python programs.