Python Constructor init Method

Python Constructors

Python Constructor

A constructor is a unique kind of method (function) that serves to set up the instance variables of a class.

In both C++ and Java, the constructor shares its name with the class it belongs to; however, Python handles constructors in a distinct manner. In Python, a constructor is utilized for the purpose of instantiating an object.

Types of Constructor

Constructors can be classified into two categories.

  • Constructor with Parameters
  • Constructor without Parameters

The definition of a constructor is invoked when an object of the respective class is instantiated. Additionally, constructors ensure that sufficient resources are available for the object to execute any initialization procedures.

Creating the constructor in python

In Python, the init function acts as the constructor for a class. This function is invoked when an instance of the class is created. It takes the self keyword as its initial parameter, which enables access to the class's attributes and methods.

When instantiating a class object, we are able to provide any quantity of arguments based on the specifications outlined in the init method. This functionality is primarily utilized for setting up the attributes of the class. It is essential for every class to include a constructor, even if it merely utilizes the automatic default constructor.

Python Example to Create the Constructor

Examine the subsequent illustration for the purpose of setting up the attributes of the Employee class.

Example

class Employee:

    def __init__(self, name, id):

        self.id = id

        self.name = name

    def display(self):

        print("ID: %d \nName: %s" % (self.id, self.name))

emp1 = Employee("John", 101)

emp2 = Employee("David", 102)

# accessing display() method to print employee 1 information

emp1.display()

# accessing display() method to print employee 2 information

emp2.display()

Output:

Output

ID: 101

Name: John

ID: 102

Name: David

Counting the number of objects of a class

The constructor is invoked automatically upon the instantiation of a class object. Take a look at the example below.

Example

Example

class Student:

    count = 0

    def __init__(self):

        Student.count = Student.count + 1

s1=Student()

s2=Student()

s3=Student()

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

Output:

Output

The number of students: 3

Python Non-Parameterized Constructor

The non-parameterized constructor is utilized when there is no intention to modify any values, or it functions as a constructor that solely accepts 'self' as its parameter. Take a look at the example below.

Example

Example

class Student:

    # Constructor - non parameterized

    def __init__(self):

        print("This is non parametrized constructor")

    def show(self,name):

        print("Hello",name)

student = Student()

student.show("John")

Python Parameterized Constructor

The parameterized constructor includes several parameters in addition to the self parameter. Take a look at the example provided below.

Example

Example

class Student:

    # Constructor - parameterized

    def __init__(self, name):

        print("This is parametrized constructor")

        self.name = name

    def show(self):

        print("Hello",self.name)

student = Student("John")

student.show()

Output:

Output

This is parametrized constructor

Hello John

Python Default Constructor

If a constructor is not specified within a class or if it is inadvertently omitted, the class will utilize a default constructor. This constructor does not execute any specific operations; rather, it serves the purpose of initializing the objects. Examine the example provided below.

Example

Example

class Student:

    roll_num = 101

    name = "Rahul"

    def display(self):

        print(self.roll_num,self.name)

st = Student()

st.display()

Output:

Output

101 Joseph

More than One Constructor in Single class

Let’s examine a different situation: what occurs if we define two identical constructors within the same class.

Example

Example

class Student:

    def __init__(self):

        print("The First Constructor")

    def __init__(self):

        print("The second contructor")

st = Student()

Output:

Output

The Second Constructor

In the code presented above, the object named st refers to the second constructor, despite both constructors having identical configurations. The first method cannot be accessed through the st object. When a class contains multiple constructors, the object of that class will invariably invoke the most recent constructor.

Note: The constructor overloading is not allowed in Python.

Python built-in class functions

The functions that are inherently defined within the class are outlined in the table below.

SN Function Description
1 getattr(obj,name,default) It is used to access the attribute of the object.
2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object.
3 delattr(obj, name) It is used to delete a specific attribute.
4 hasattr(obj, name) It returns true if the object contains some specific attribute.

Example

Example

class Student:

    def __init__(self, name, id, age):

        self.name = name

        self.id = id

        self.age = age

    # creates the object of the class Student

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

# prints the attribute name of the object s

print(getattr(s, 'name'))

# reset the value of attribute age to 23

setattr(s, "age", 23)

# prints the modified value of age

print(getattr(s, 'age'))

# prints true if the student contains the attribute with name id

print(hasattr(s, 'id'))

# deletes the attribute age

delattr(s, 'age')

# this will give an error since the attribute age has been deleted

print(s.age)

Output:

Output

John

23

True

AttributeError: 'Student' object has no attribute 'age'

Built-in class attributes

In addition to various other attributes, a Python class encompasses certain built-in class attributes that offer insights regarding the class itself.

The following table presents the attributes that are integrated into the class.

SN Attribute Description
1 dict It provides the dictionary containing the information about the class namespace.
2 doc It contains a string which has the class documentation
3 name It is used to access the class name.
4 module It is used to access the module in which, this class is defined.
5 bases It contains a tuple including all base classes.

Example

Example

class Student:

    def __init__(self,name,id,age):

        self.name = name;

        self.id = id;

        self.age = age

    def display_details(self):

        print("Name:%s, ID:%d, age:%d"%(self.name,self.id))

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

print(s.__doc__)

print(s.__dict__)

print(s.__module__)

Output:

Output

None

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

__main__

Input Required

This code uses input(). Please provide values below: