Python

Python Constructor: A Guide to Initializing Objects in Python

Python Constructor: A Guide to Initializing Objects in Python

Python Constructor

A constructor is a special method in Python that is used to initialize the attributes of an object when a class instance is created. Unlike languages such as C++ and Java, where constructors generally use the same name as the class, Python uses the __init__() method for object initialization.

The constructor is automatically called when an object is created. It can be used to assign initial values to instance attributes and perform other startup tasks required by the object.

Python constructors are commonly discussed in two forms:

  1. Parameterized Constructor
  2. Non-Parameterized Constructor

In this tutorial, we will understand how constructors work in Python, explore different constructor examples, learn about constructor behavior, and examine useful built-in class functions and attributes.

Python Constructor
Python Constructor

Creating a Constructor in Python

In Python, the __init__() method acts as the constructor. It is automatically called whenever an instance of a class is created.

The self parameter is passed as the first argument and represents the current object. It allows the constructor to access and initialize the attributes and methods associated with that object.

Depending on the requirements of the class, additional arguments can be passed to __init__().

Parameterized Constructor

A parameterized constructor accepts additional arguments besides self. These arguments can be used to initialize instance attributes with specific values.

Example

class Employee:
    def __init__(self, name, id):
        self.name = name
        self.id = id

    def display(self):
        print(f"ID: {self.id}\nName: {self.name}")


emp1 = Employee("John", 101)
emp2 = Employee("David", 102)

emp1.display()
emp2.display()

Output

ID: 101
Name: John
ID: 102
Name: David

Here, the name and id values are supplied while creating the objects. The constructor stores these values in the corresponding instance attributes.

Counting the Number of Objects in a Class

Because the constructor is automatically called whenever an object is created, it can also be used to keep track of the number of objects created from a class.

Example

class Student:
    count = 0

    def __init__(self):
        Student.count += 1


s1 = Student()
s2 = Student()
s3 = Student()

print("The number of students:", Student.count)

Output

The number of students: 3

Every time a Student object is created, the __init__() method increases the value of Student.count by one.

Non-Parameterized Constructor

A non-parameterized constructor does not accept additional arguments apart from self. It can be useful when an object does not require specific values during initialization.

Example

class Student:
    def __init__(self):
        print("This is a non-parameterized constructor")

    def show(self, name):
        print(f"Hello, {name}")


student = Student()
student.show("John")

Output

This is a non-parameterized constructor
Hello, John

When Student() is created, the constructor runs automatically and displays the first message.

Another Parameterized Constructor Example

A parameterized constructor can also be used to store a value and access it later through another method.

class Student:
    def __init__(self, name):
        print("This is a parameterized constructor")
        self.name = name

    def show(self):
        print(f"Hello, {self.name}")


student = Student("John")
student.show()

Output

This is a parameterized constructor
Hello, John

The constructor receives "John", stores it in self.name, and the show() method later uses that stored value.

Default Constructor

If a constructor is not explicitly defined in a class, Python provides default object initialization behavior. This allows an object to be created without defining custom initialization logic.

Example

class Student:
    roll_num = 101
    name = "Joseph"

    def display(self):
        print(self.roll_num, self.name)


st = Student()
st.display()

Output

101 Joseph

In this example, no __init__() method is explicitly defined. The class attributes can still be accessed through the object.

Multiple Constructors in a Class

Python does not support traditional constructor overloading in the same way as some other programming languages. If multiple methods with the same name are defined inside a class, the later definition replaces the earlier one.

Example

class Student:
    def __init__(self):
        print("The first constructor")

    def __init__(self):
        print("The second constructor")


st = Student()

Output

The second constructor

The second __init__() definition replaces the first one. Therefore, when the object is created, only the second constructor is executed.

Python Built-in Class Functions

Python provides several built-in functions that can be used to work with attributes of objects.

FunctionDescription
getattr(obj, name)Accesses the specified attribute of an object.
setattr(obj, name, value)Sets a specific attribute to a particular value.
delattr(obj, name)Deletes a specified attribute from an object.
hasattr(obj, name)Checks whether an object contains a specific attribute.

Example

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


s = Student("John", 101, 22)

print(getattr(s, 'name'))

setattr(s, "age", 23)
print(getattr(s, 'age'))

print(hasattr(s, 'id'))

delattr(s, 'age')

# The following line will raise an AttributeError
# print(s.age)

Output

John
23
True

After delattr(s, 'age') is executed, the age attribute is removed from the object. Trying to access s.age afterward would raise an AttributeError.

Python Built-in Class Attributes

Python classes and objects provide several built-in attributes that can be used to obtain information about a class or its namespace.

AttributeDescription
__dict__Contains the namespace information associated with the class or object.
__doc__Contains the documentation string of the class when one is defined.
__name__Represents the name of the class.
__module__Specifies the module in which the class is defined.
__bases__Contains a tuple of the base classes of a class.

Example

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


s = Student("John", 101, 22)

print(s.__doc__)
print(s.__dict__)
print(s.__module__)

Output

None
{'name': 'John', 'id': 101, 'age': 22}
__main__

The __dict__ output shows the instance attributes created by the constructor. The __doc__ value is None because no documentation string was defined in the class, while __module__ shows the module where the class is defined.

Complete Advance AI Topics: Click Here
SQL Tutorial:
Click Here
YT:- DecodeIT

Frequently Asked Questions

1. What is a constructor in Python?

A constructor is the __init__() method used to initialize an object’s attributes when an instance of a class is created.

2. Which method is used as a constructor in Python?

The __init__() method is used for initializing objects in Python.

3. What is a parameterized constructor?

A parameterized constructor accepts additional arguments and uses them to initialize instance attributes.

4. What is a non-parameterized constructor?

A non-parameterized constructor only uses self and does not receive additional initialization arguments.

5. Does Python support constructor overloading?

Python does not support traditional constructor overloading. If multiple __init__() methods are defined in the same class, the last definition replaces the earlier one.

6. What is the purpose of self in a constructor?

The self parameter refers to the current object and allows the constructor to initialize and access its instance attributes.

7. What does getattr() do in Python?

getattr() retrieves the value of a specified attribute from an object.

8. What does hasattr() check?

hasattr() checks whether an object contains a particular attribute and returns a Boolean result.

9. What is __dict__ in Python?

__dict__ provides dictionary-based information about the namespace and attributes associated with a class or object.

10. Can a class work without explicitly defining __init__()?

Yes. A class can be created without explicitly defining an __init__() method when custom initialization is not required.

Conclusion

Constructors are an important part of Python classes because they provide a way to initialize objects when they are created. The __init__() method serves as the constructor and can be used with or without additional parameters depending on the requirements of the class.

Python supports parameterized and non-parameterized constructor patterns, while multiple definitions of __init__() are not retained as overloaded constructors. Constructors can also be used for tasks such as initializing attributes and counting created objects.

Along with constructors, built-in functions such as getattr(), setattr(), delattr(), and hasattr(), as well as class attributes such as __dict__, __doc__, and __module__, provide useful ways to work with Python objects and classes.

Keywords: Python Constructor, python constructor example, python constructor class, python constructor arguments, python constructor overloading, python constructor default values, python constructor vs initializer, python constructor optional arguments, python constructor and destructor, class and object in Python example, Python class example, what is object in Python, what is class in Python, Python class function, Python class inheritance, dataclass Python constructor,Python Constructor

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

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

Chat with us