The Wayback Machine - https://web.archive.org/web/20230513142350/https://www.geeksforgeeks.org/constructors-in-python/amp/

Constructors in Python

Prerequisites: Object-Oriented Programming in Python, Object-Oriented Programming in Python | Set 2 
Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. In Python the __init__() method is called the constructor and is always called when an object is created.
Syntax of constructor declaration : 

def __init__(self):
    # body of the constructor

Types of constructors : 

Example of default constructor : 
 




class GeekforGeeks:
 
    # default constructor
    def __init__(self):
        self.geek = "GeekforGeeks"
 
    # a method for printing data members
    def print_Geek(self):
        print(self.geek)
 
 
# creating object of the class
obj = GeekforGeeks()
 
# calling the instance method using the object obj
obj.print_Geek()
Output
GeekforGeeks

Example of the parameterized constructor : 




class Addition:
    first = 0
    second = 0
    answer = 0
 
    # parameterized constructor
    def __init__(self, f, s):
        self.first = f
        self.second = s
 
    def display(self):
        print("First number = " + str(self.first))
        print("Second number = " + str(self.second))
        print("Addition of two numbers = " + str(self.answer))
 
    def calculate(self):
        self.answer = self.first + self.second
 
 
# creating object of the class
# this will invoke parameterized constructor
obj1 = Addition(1000, 2000)
 
# creating second object of same class
obj2 = Addition(10, 20)
 
# perform Addition on obj1
obj1.calculate()
 
# perform Addition on obj2
obj2.calculate()
 
# display result of obj1
obj1.display()
 
# display result of obj2
obj2.display()
Output
First number = 1000
Second number = 2000
Addition of two numbers = 3000
First number = 10
Second number = 20
Addition of two numbers = 30

Example:




class MyClass:
    def __init__(self, name=None):
        if name is None:
            print("Default constructor called")
        else:
            self.name = name
            print("Parameterized constructor called with name", self.name)
     
    def method(self):
        if hasattr(self, 'name'):
            print("Method called with name", self.name)
        else:
            print("Method called without a name")
 
# Create an object of the class using the default constructor
obj1 = MyClass()
 
# Call a method of the class
obj1.method()
 
# Create an object of the class using the parameterized constructor
obj2 = MyClass("John")
 
# Call a method of the class
obj2.method()
Output
Default constructor called
Method called without a name
('Parameterized constructor called with name', 'John')
('Method called with name', 'John')

Explanation:

In this example, we define a class MyClass with both a default constructor and a parameterized constructor. The default constructor checks whether a parameter has been passed in or not, and prints a message to the console accordingly. The parameterized constructor takes in a single parameter name and sets the name attribute of the object to the value of that parameter.

We also define a method method() that checks whether the object has a name attribute or not, and prints a message to the console accordingly.

We create two objects of the class MyClass using both types of constructors. First, we create an object using the default constructor, which prints the message “Default constructor called” to the console. We then call the method() method on this object, which prints the message “Method called without a name” to the console.

Next, we create an object using the parameterized constructor, passing in the name “John”. The constructor is called automatically, and the message “Parameterized constructor called with name John” is printed to the console. We then call the method() method on this object, which prints the message “Method called with name John” to the console.

Overall, this example shows how both types of constructors can be implemented in a single class in Python.

Advantages of using constructors in Python:

Disadvantages of using constructors in Python:

Overall, constructors in Python can be useful for initializing objects and enforcing encapsulation. However, they may not always be necessary and are limited in their functionality compared to constructors in other programming languages.


Article Tags :