constructores-en-python

Constructors in Python

  • 2 min

A constructor in Python is a special method __init__() that is automatically called when a new instance 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, check out the Object-Oriented Programming Course

Basic Constructor Example

# 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
Copied!

In this example,

  • __init__(self, name, age) is the constructor of the Person class
  • When a new instance (person1 and person2) is created
  • Python automatically calls __init__() and passes the provided name and age arguments.

Constructor Parameters

The first parameter of __init__() is self, which represents the current instance of the class. It is used to access the instance’s attributes and methods within the method itself and in other class methods.

Besides 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
Copied!

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 a constructor (__init__()) is not defined, Python provides a default one that does not initialize any attributes.