Python Constructor Tutorial

Python constructors are used to creating new instances or objects. User-defined classes or Python-provided objects can be created using a constructer. The constructer is defined with the def __init__() function definition inside the class definition.

Default Constructor

The default constructor is used to create an object without providing any parameter dynamically. The object is constructed with default values. Only the self of the object is provided to the constructor method as a parameter to set default values for this object. In the following example, we set the objects name property as ferrari .

class Car:
   def __init__(self):
      self.name="ferrari"


f = Car()

print(f.name)

Parameterized Constructor

In some cases, we may want to provide some values for the initialized object. These values can be provided to the constructor as parameters and this is called as parameterized constructor . In the following example, we provide the name value as a parameter.

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


f = Car("ferrari")

print(f.name)

Leave a Comment