Parameterized constructor in Python | Example code

A constructor with a Parameter is called Parameterized constructor in Python. Parameters could be one, two, or more.

Example Parameterized constructor in Python

Simple example code accepts the arguments during object creation then such types of constructors are known as Parameterized constructors.

We can pass the values (data) during object creation. It will set custom values for instance variables.

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age


# create object
stud = Student("John", 15)
print(stud.name, stud.age)

Output:

Parameterized constructor in Python

How to return string from the parameterized constructor in Python?

Python class constructor example.

class Human:
    def __init__(self, name):
        self.name = name


obj = Human("Bob")
print(obj.name)  

Output: Bob

Do comment if you have any doubts and suggestions on this Python constructor topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.