Interview Questions, Answers and Tutorials

Constructor and destructor methods

Constructor and destructor methods

Hey there! 🌟 Today, we will dive into a super cool topic in Python called Constructor and Destructor Methods. Don’t let the fancy names scare you off! We’ll break it down step by step, and by the end, you’ll be a pro at understanding them.

What are Constructor and Destructor Methods?

Imagine you’re building a house with LEGO bricks. Before you start building, you need to decide what kind of house you want, right? Constructor methods are like the blueprint for your house. They help create an object when you’re working with classes in Python.

Now, once your LEGO house is built and you’re done playing with it, you might want to clean up and put the bricks back in the box. Destructor methods help with this cleanup process. They’re like your mom saying, “Time to clean up!” when you’re done playing.

Constructor Method: __init__()

In Python, the constructor method is called __init__(). It’s like the magical spell that brings your objects to life! Let’s see it in action:

class Dog:
    def __init__(self, name, breed): = name
        self.breed = breed

my_dog = Dog("Buddy", "Labrador")
print("My dog's name is",
print("My dog's breed is", my_dog.breed)

In this example, we created a class called Dog with a constructor method __init__(). When we create a Dog object (my_dog), we pass values for name and breed, and the constructor method sets those values for the object.

Destructor Method: __del__()

Now, let’s talk about cleaning up! The destructor method in Python is called __del__(). It helps in freeing up resources when an object is no longer needed. Check this out:

class Car:
    def __init__(self, brand):
        self.brand = brand
    def __del__(self):
        print(self.brand, "car is being destroyed!")

my_car = Car("Toyota")
del my_car  # Deleting the object

In this example, when we delete the my_car object using del, Python automatically calls the destructor method __del__(), and it prints a message saying the car is being destroyed.

Practice Questions:
  1. What is the purpose of a constructor method in Python?
    • A) To destroy objects
    • B) To create objects
    • C) To clean up resources
    • D) To print messages

  1. What is the name of the constructor method in Python?
    • A) __init__()
    • B) __constructor__()
    • C) __create__()
    • D) __start__()

  1. Answer: B) To create objects
  2. Answer: A) __init__()

Great job! You’ve now learned about constructor and destructor methods in Python. Now you can create and clean up objects like a pro! 🚀 Keep practicing, and soon you’ll be a Python guru! If you have any questions, feel free to ask.