Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Object-oriented Programmi...
  5. Constructors in Python

Constructors in Python

Constructors in Python is defined as a special method used to initialize newly created objects.

  • It is a method that is automatically called when an object of a class is instantiated.
  • The constructor is used to set up initial values for the object’s attributes and to perform any setup actions.

A constructor is defined by the __init__() method. It is called when an instance of a class is created and allows you to assign values to the object’s attributes.

Syntax:

class ClassName:
    def __init__(self, parameters):
        # constructor body
        self.attribute = parameters

Here, __init__ is the constructor method, and self refers to the current instance of the class. The parameters passed to the constructor are used to initialize the object’s attributes.

Example of a Constructor:

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

    def display(self):
        print(f"Name: {self.name}, Age: {self.age}")

# Create an instance of Person
person1 = Person("Alice", 30)

# Display the object's attributes
person1.display()  # Output: Name: Alice, Age: 30

1.) Default Constructor:

  • A constructor that does not take any arguments except self. It is used to initialize the object with default values.

Example:

class Car:
    def __init__(self):
        self.model = "Unknown"
        self.year = 2000

car1 = Car()
print(car1.model)  # Output: Unknown
print(car1.year)   # Output: 2000

2.) Parameterized Constructor:

  • A constructor that takes arguments and uses them to initialize the object with custom values.

Example:

class Car:
    def __init__(self, model, year):
        self.model = model
        self.year = year

car1 = Car("Toyota", 2021)
print(car1.model)  # Output: Toyota
print(car1.year)   # Output: 2021

Why Use Constructors?

  • Encapsulation: The constructor allows you to encapsulate the initialization logic and keep the object setup in one place.
  • Simplicity: It simplifies the process of creating objects with a defined state, ensuring that objects are always initialized properly.
  • Code Reusability: Constructors allow for easy initialization of multiple objects with different initial values.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *