Open In App

Constructors in Python

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 : 

  • default constructor: The default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.
  • parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.


Example of default constructor : 
 

Python3
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 : 

Python3
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:

Python
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:

  • Initialization of objects: Constructors are used to initialize the objects of a class. They allow you to set default values for attributes or properties, and also allow you to initialize the object with custom data.
  • Easy to implement: Constructors are easy to implement in Python, and can be defined using the __init__() method.
  • Better readability: Constructors improve the readability of the code by making it clear what values are being initialized and how they are being initialized.
  • Encapsulation: Constructors can be used to enforce encapsulation, by ensuring that the object’s attributes are initialized correctly and in a controlled manner.

Disadvantages of using constructors in Python:

  • Overloading not supported: Unlike other object-oriented languages, Python does not support method overloading. This means that you cannot have multiple constructors with different parameters in a single class.
  • Limited functionality: Constructors in Python are limited in their functionality compared to constructors in other programming languages. For example, Python does not have constructors with access modifiers like public, private or protected.
  • Constructors may be unnecessary: In some cases, constructors may not be necessary, as the default values of attributes may be sufficient. In these cases, using a constructor may add unnecessary complexity to the code.

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.

Constructors in Python – FAQs

Is __init__ a constructor in Python?

Yes, __init__ is considered a constructor in Python. It is a special method that is automatically called when an instance (object) of a class is created. Its primary purpose is to initialize the attributes of the object.

What are the different types of construction in Python?

In Python, there is primarily one type of constructor:

  • __init__ Constructor: This is the standard constructor used in Python classes. It initializes the attributes of an object when it is instantiated.

Can we have two __init__ in Python?

No, you cannot have two __init__ methods with the same name in a single class in Python. Python does not support method overloading based on the number or types of arguments, unlike some other programming languages.

Can we overload constructors in Python?

While Python does not support method overloading in the traditional sense (having multiple methods with the same name but different parameters), you can achieve a form of constructor overloading using default parameter values or by using class methods that act as alternative constructors. Here’s an example:

class Person:
def __init__(self, name=None, age=None):
if name is not None and age is not None:
self.name = name
self.age = age
else:
self.name = "Unknown"
self.age = 0

@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, 2024 - birth_year)

# Using default constructor
person1 = Person("Alice", 30)
print(person1.name, person1.age) # Output: Alice 30

# Using alternative constructor
person2 = Person.from_birth_year("Bob", 1990)
print(person2.name, person2.age) # Output: Bob 34

How to call a constructor in Python?

The constructor (__init__ method) in Python is automatically called when you create an instance (object) of a class using the class name followed by parentheses (). Here’s an example:

class MyClass:
def __init__(self, param):
self.param = param

# Creating an instance of MyClass
obj = MyClass(10) # Calls __init__(self, param=10)


Previous Article
Next Article

Similar Reads

What is a clean and Pythonic way to have multiple constructors in Python?
Python does not support explicit multiple constructors, yet there are some ways to achieve multiple constructors. We use Python's inbuilt __init__ method to define the constructor of a class. It tells what will the constructor do if the class object is created. If multiple __init__ methods are written for the same class, then the latest one overwri
7 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Visualizing O(n) using Python
Introduction Algorithm complexity can be a difficult concept to grasp, even presented with compelling mathematical arguments. This article presents a tiny Python program that shows the relative complexity of several typical functions. It can be easily adapted to other functions. Complexity. Why it matters? Computational complexity is a venerable su
3 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Article Tags :
Practice Tags :