A constructor in Python is a special method __init__()
that is automatically called when a new instance (object) of a class is created.
Its main function is to initialize the instance’s attributes with default or custom values.
If you want to learn more
consult the Introduction to Programming Course read more ⯈
Basic Constructor Example
# Definition of a class with a constructor
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating instances using the constructor
person1 = Person("Juan", 30)
person2 = Person("María", 25)
# Accessing the attributes of the instances
print(person1.name, person1.age) # Output: Juan 30
print(person2.name, person2.age) # Output: María 25
In this example,
__init__(self, name, age)
is the constructor of thePerson
class- When a new instance is created (
person1
andperson2
) - Python automatically calls
__init__()
and passes the provided argumentsname
andage
.
Constructor Parameters
The first parameter of __init__()
is self
, which represents the current instance of the class. It is used to access the attributes and methods of the instance within the method itself and in other methods of the class.
In addition to self
, the constructor can accept any number of parameters needed to initialize the instance. These parameters are provided when creating the instance.
Defining Optional Attributes
Constructors can define optional attributes with default values.
class Car:
def __init__(self, brand, model, color="black"):
self.brand = brand
self.model = model
self.color = color
# Creating instances
car1 = Car("Toyota", "Corolla")
car2 = Car("Tesla", "Model S", "red")
print(car1.brand, car1.model, car1.color) # Output: Toyota Corolla black
print(car2.brand, car2.model, car2.color) # Output: Tesla Model S red
In this example, Car
has an optional attribute color
with a default value of "black"
. A different color can be provided when creating the instance (car2
).
Default Constructor
If no constructor (__init__()
) is defined, Python provides a default one that does not initialize any attributes.