class ClassName: def __init__(self):
Examples of different types of constructors in Python
Simple example code.
It is a simple constructor without any argument to pass. Its definition has only one argument which is a reference to the instance being constructed.
class Test: def __init__(self): self.str1 = "Default" print("Test", self.str1) obj = Test()
If the constructor has parameters then it’s known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self.
class Person: def __init__(self, name, userid): self.name = name self.userid = userid obj = Person('John', '[email protected]') print(obj.userid)
Output: [email protected]
Do comment if you have any doubts and suggestions on this Python constructor tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.