Python Constructor

A constructor is used to initialize a class when its instance is created. The first parameter of the constructor is always “self”. Constructor in Python is created using a special function known as  __init__() function.

Loading...

How to Create a  constructor in Python?

A constructor in Python can be created using __init__() function that can take any number of parameters with self as a first parameter. Let us consider the following example to create an Employee class with three attributes, id, name, and department.

class Employee:

    def __init__(self, id, name, department):
        self.id = id
        self.name = name
        self.department = department

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


emp1 = Employee(1,"John Doe", "Web Development")
emp2 = Employee(2,"Ryan Rees", "Mobile Development")

emp1.display()
emp2.display()

The output of the above program is:-

ID: 1
Name: John Doe
Department: Web Development
ID: 2
Name: Ryan Rees
Department: Mobile Development
The example given above is of the parameterized constructor. Python can also have no parameterized constructor where the constructor doesn’t receive any parameters.
class Student:
    def __init__(self):
        print("This is non parametrized constructor")

    def show(self, name):
        print("Hello", name)


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

Output:-

This is non parametrized constructor
Hello John Snow
Loading...
SHARE Python Constructor

You may also like...

Leave a Reply

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

Share