Python Constructor: A Guide to Initializing Objects in Python

Python Constructor

A constructor is a special type of method in Python that is used to initialize the instance attributes of a class. While constructors in C++ or Java share the same name as their class, Python handles constructors differently, utilizing a method named __init__() to serve this purpose. Constructors are essential for creating objects and ensuring they have the required resources to perform startup tasks.

Python provides two types of constructors:

  1. Parameterized Constructor
  2. Non-parameterized Constructor

Let’s dive deeper into constructors in Python, their implementation, and their practical use cases.

Complete Python Course with Advance topics:- CLICK HERE


Creating a Constructor in Python

In Python, the __init__() method acts as the constructor. This method is automatically called when a class instance is created. The self keyword, passed as the first argument, allows access to the class’s attributes and methods.

You can pass multiple arguments to the __init__() method depending on the initialization needs of the class. Even if you don’t define a constructor, Python provides a default one.

Example: Parameterized Constructor

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


Counting the Number of Objects in a Class

Since the constructor is automatically called during object creation, it can be used to count the total number of objects created.

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


Non-Parameterized Constructor

A non-parameterized constructor does not accept additional arguments other than self. It’s useful when there’s no need to initialize attributes with specific values.

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


Parameterized Constructor

A parameterized constructor allows passing arguments to initialize instance attributes.

Example:

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


Default Constructor

When a constructor isn’t explicitly defined, Python provides a default constructor that initializes objects without custom 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


Multiple Constructors in a Class

In Python, if multiple constructors are defined, only the last one is retained. Constructor overloading is not allowed.

Example:

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

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

st = Student()

Output:

The second constructor


Python Built-in Class Functions

Python provides several built-in functions to work with object attributes.

Function Description
getattr(obj, name) Accesses the attribute of an object.
setattr(obj, name, value) Sets a specific attribute to a particular value.
delattr(obj, name) Deletes a specific attribute.
hasattr(obj, name) Checks if 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
AttributeError: 'Student' object has no attribute 'age'


Python Built-in Class Attributes

Python classes include several built-in attributes that provide information about the class itself.

Attribute Description
__dict__ Dictionary with the class’s namespace.
__doc__ Documentation string for the class.
__name__ Name of the class.
__module__ Module in which the class is defined.
__bases__ Tuple containing all base classes of the 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__


Python Classes and Objects: A Guide to Mastering Object-Oriented Programming
https://updategadh.com/python/python-classes-and-objects/
Python OOPs Concepts: A Complete Guide
https://updategadh.com/python/python-oops-concepts-a-complete-guide/
Finding the Second Largest Number in Python
https://updategadh.com/python/finding-the-second-largest-number/
Python SimpleImputer Module: A Comprehensive Guide
https://updategadh.com/python/python-simpleimputer-module/
Python OpenCV Object Detection: A Step-by-Step Guide
https://updategadh.com/python/python-opencv-object-detection/

Download New Real Time Projects :-Click here


class and object in python example
python class example
what is object in python
what is class in python
python class function
what is object in python with example
python class(object) vs class
python class inheritance
python constructor
python constructor overloading
dataclass python constructor
python constructor class
python constructor default values
python constructor vs initializer
python constructor optional arguments
python constructor example
python constructor arguments
python constructor and destructor example
python constructor and destructor
python constructor args

See also  PySpark MLlib: Empowering Machine Learning with Big Data

Post Comment