Constructors and Destructors - Rybd04/2143-OOP GitHub Wiki

Definition

Constructors

A constructor is a special method that is automatically called when an object is created. It is used to initialize the object’s state

Destructors

A destructor is a special method that is automatically called when an object is destroyed. It is used to clean up resources such as closing files or network connections.

Explanation

Constructor

Creates an instance of an object with basic values.

Destructor

Deletes objects

Basic Code Example

Constructor

class Person:
    def __init__(self, name):  # constructor
        self.name = name

p = Person("Alice")  # __init__ is called
print(p.name)         # Output: Alice

Destructor

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

    def __del__(self):  # destructor
        print(f"{self.name} is being deleted")

p = Person("Bob")
del p  # Triggers __del__

Image

image

Additional Resources

https://www.geeksforgeeks.org/difference-between-constructor-and-destructor-in-c/ https://www.codementor.io/@supernerdd7/constructor-and-destructor-in-c-1r8kkogm6j