A constructor in Python is a special method __init__()
that is called automatically when a new instance of a class is created.
Its main function is to initialize the instance attributes with default or custom values.
If you want to learn more about Constructors
check the Object-Oriented Programming Course read more
Basic example of a constructor
# Class definition with constructor
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating instances using the constructor
person1 = Person("Luis", 30)
person2 = Person("María", 25)
# Accessing instance attributes
print(person1.name, person1.age) # Output: Luis 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 providedname
andage
arguments.
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.
Definition of 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.