Home » Python Constructors Tutorial with Examples

Python Constructors Tutorial with Examples

Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification

In Python, constructors are special methods used to initialize objects when they are created.

Constructors allow you to set up initial values for the attributes of a class, providing an organized way to handle object creation.

In this tutorial, we will cover:

  1. What is a Constructor in Python?
  2. Types of Constructors in Python
  3. The __init__() Method (Default Constructor)
  4. Parameterized Constructors
  5. Constructor with Default Arguments
  6. Using self in Constructors
  7. Destructor (__del__() method)
  8. Examples and Use Cases of Constructors

Let’s explore each topic with examples and explanations.

1. What is a Constructor in Python?

A constructor is a special method in a class that is automatically called when an object is created. It is used to initialize the object’s state (i.e., assign values to the object’s attributes). In Python, constructors are defined using the __init__() method.

  • The constructor in Python is invoked when an object is created from a class.
  • Constructors can accept arguments and assign values to the object's attributes during initialization.

2. Types of Constructors in Python

There are two types of constructors in Python:

  1. Default Constructor: A constructor that takes no parameters (except self) and initializes the object with default values.
  2. Parameterized Constructor: A constructor that accepts parameters to initialize the object with specific values.

3. The __init__() Method (Default Constructor)

In Python, the constructor is defined using the __init__() method. This method is called automatically when an instance of a class is created. The __init__() method takes the self parameter, which refers to the instance of the object being created.

Example: Default Constructor (No Parameters)

class Car:
    def __init__(self):
        self.make = "Toyota"
        self.model = "Corolla"
    
    def display_info(self):
        print(f"Car make: {self.make}, Model: {self.model}")

# Creating an instance of the Car class
my_car = Car()
my_car.display_info()

Output:

Car make: Toyota, Model: Corolla
  • In this example, the __init__() method initializes the make and model attributes with default values. When we create an instance of the Car class (my_car), the constructor is called automatically.

4. Parameterized Constructors

A parameterized constructor accepts arguments and uses them to initialize the object’s attributes. This allows you to create objects with different values by passing arguments during object creation.

Example: Parameterized Constructor

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model
    
    def display_info(self):
        print(f"Car make: {self.make}, Model: {self.model}")

# Creating instances of the Car class with different values
car1 = Car("Honda", "Civic")
car2 = Car("Ford", "Mustang")

car1.display_info()  # Output: Car make: Honda, Model: Civic
car2.display_info()  # Output: Car make: Ford, Model: Mustang

Output:

Car make: Honda, Model: Civic
Car make: Ford, Model: Mustang
  • In this example, the constructor takes make and model as arguments, allowing us to create different Car objects with unique values.

5. Constructor with Default Arguments

You can define a constructor with default arguments so that if some arguments are not provided during object creation, the constructor will use default values.

Example: Constructor with Default Arguments

class Car:
    def __init__(self, make="Toyota", model="Corolla"):
        self.make = make
        self.model = model
    
    def display_info(self):
        print(f"Car make: {self.make}, Model: {self.model}")

# Creating instances with and without passing arguments
car1 = Car()  # Uses default values
car2 = Car("Honda", "Civic")  # Passes arguments

car1.display_info()  # Output: Car make: Toyota, Model: Corolla
car2.display_info()  # Output: Car make: Honda, Model: Civic

Output:

Car make: Toyota, Model: Corolla
Car make: Honda, Model: Civic
  • In this example, the constructor uses default values (make=”Toyota” and model=”Corolla”) if no arguments are provided. If arguments are passed, those values override the defaults.

6. Using self in Constructors

In Python, the self parameter refers to the instance of the object. It allows you to access the attributes and methods of the object within the class. In constructors, self is used to initialize the object’s attributes and methods.

Example: Understanding self

class Person:
    def __init__(self, name, age):
        self.name = name  # 'self.name' refers to the instance variable
        self.age = age
    
    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an instance of the Person class
person = Person("Alice", 30)
person.greet()

Output:

Hello, my name is Alice and I am 30 years old.
  • In this example, self.name and self.age refer to the attributes of the Person instance. The greet() method uses self to access these attributes.

7. Destructor (__del__() Method)

A destructor in Python is called when an object is about to be destroyed. It is defined using the __del__() method. Python automatically manages memory, but if you want to perform cleanup tasks, you can use a destructor.

Example: Using a Destructor

class Person:
    def __init__(self, name):
        self.name = name
        print(f"{self.name} is created.")
    
    def __del__(self):
        print(f"{self.name} is destroyed.")

# Creating and deleting an object
person = Person("John")
del person

Output:

John is created.
John is destroyed.
  • In this example, the destructor __del__() is called when the person object is deleted using del person.

8. Examples and Use Cases of Constructors

Example 1: Constructor for Initializing Bank Accounts

class BankAccount:
    def __init__(self, account_holder, balance=0):
        self.account_holder = account_holder
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print(f"${amount} deposited. New balance: ${self.balance}")
    
    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient balance!")
        else:
            self.balance -= amount
            print(f"${amount} withdrawn. New balance: ${self.balance}")

# Creating a bank account object
account = BankAccount("Alice", 500)

# Performing deposit and withdrawal operations
account.deposit(200)  # Output: $200 deposited. New balance: $700
account.withdraw(100)  # Output: $100 withdrawn. New balance: $600

Example 2: Constructor with Nested Objects

class Address:
    def __init__(self, street, city, country):
        self.street = street
        self.city = city
        self.country = country

class Person:
    def __init__(self, name, address):
        self.name = name
        self.address = address  # Storing an Address object
    
    def display_info(self):
        print(f"Name: {self.name}")
        print(f"Address: {self.address.street}, {self.address.city}, {self.address.country}")

# Creating an Address object
address = Address("123 Main St", "New York", "USA")

# Creating a Person object with the Address object
person = Person("John Doe", address)
person.display_info()

Output:

Name: John Doe
Address: 123 Main St, New York, USA
  • In this example, a Person object contains an Address object, showing how constructors can initialize objects that contain other objects.

Summary of Python Constructors:

Concept Description
Default Constructor Initializes object with default values.
Parameterized Constructor Accepts arguments to initialize object attributes with specific values.
__init__() Method The constructor method called when an object is created.
self Parameter Refers to the instance of the object and is used to access attributes and methods.
Constructor with Default Arguments Allows some arguments to have default values if not provided during object creation.
Destructor (__del__()) Called when an object is about to be destroyed to perform cleanup tasks.

Conclusion

Constructors in Python are essential for initializing objects and setting their initial state. In this tutorial, we covered:

  • Types of constructors: Default constructors and parameterized constructors.
  • How to use the **`__

init__()` method** to define constructors.

  • Using self to access object attributes and methods.
  • Destructors (__del__()) to handle object cleanup.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More