Class constructors are used to creating objects from classes. The contractors provide the ability to set some default and custom values for the class variables. During the instance initialization, the constructor is called with the provided parameters or without any parameters. The contractor can be defined explicitly or implicitly without writing extra code. In this tutorial, we examine Python class constructors like Default Constructor
or Parameterized Constructor
.
Default Constructor
When a Python class is defined the default constructor is created automatically. The default constructor is used to initialize instances or objects from the class without providing any external parameter. The default constructor is also very helpful because it is not defined explicitly and there is no need to write extra code. In the following example, we use the default constructor for the class Person.
class Person:
name="İsmail Baydan"
age=38
ismail = Person()
print(ismail.name)
print(ismail.age)
Parameterized Constructor (__init__)
The parameterized constructors are used to define constructors that accept parameters to set different values for the object or instance during creation. The __init__()
method is defined inside the class as the parameterized constructor. The __init__() method is defined as a regular method. The initialization parameters are provided to this __init__() method. But the first parameter of the __init__() method is the self
keyword which is used to define the instance and used to access variables and methods of the instance.
class Person:
name=""
age=-1
def __init__(self,name,age):
self.name=name
self.age=age
ismail = Person("İsmail Baydan",38)
print(ismail.name)
print(ismail.age)
Multiple Constructors
A class may have multiple constructors for different cases. Generally, the constructors are used for different counts of parameters. In the following example, we define two constructors where the first one only accepts the name as a value and the second one accepts two parameters.
class Person:
name=""
age=-1
def __init__(self,name):
self.name=name
self.age=age
def __init__(self,name,age):
self.name=name
self.age=age
ismail = Person("İsmail Baydan",38)
ali= Person("Ahmet Ali Baydan")