Lesson Overview and Plan

Welcome! Today's mission involves learning about constructors in Python, specifically focusing on the __init__ method. Constructors define the initial state of Python objects, much in the same way that a spacecraft is prepared for launch. In this lesson, we will learn about constructors, create them using the __init__ method, work with multiple objects, and understand their importance.

Introduction to Constructors

Put simply, a constructor prepares an object when it is initially created. Python works with constructors through the __init__ method.

The __init__ method sets the initialization process in motion for Python objects. You can visualize this with the following Spaceship class:

class Spaceship:
    def __init__(self):
        self.destination = "Mars"
        self.speed = 50000  # speed in mph

spaceship = Spaceship() # this calls the constructor
print(spaceship.destination) # Prints: "Mars"
print(spaceship.speed) # Prints: 50000

In this class, __init__ establishes destination and speed for a Spaceship, which doesn't require any additional input.

Creating a Constructor with __init__

The __init__ method is called automatically when an object is constructed. Upon invocation, self refers to the newly created object:

class Rocket:
    def __init__(self, name, destination):
        self.name = name
        self.destination = destination
      
rocket = Rocket("Apollo", "Moon") # Creates a rocket calling the constructor
print(rocket.name) # Prints: "Apollo"
print(rocket.destination) # Prints: "Moon"

In this example, a Rocket named "Apollo" with a destination of "Moon" is created using __init__.

Working with Multiple Objects

The __init__ method assigns unique information to each object. Here's how it works:

rocket1 = Rocket("Apollo", "Moon")
rocket2 = Rocket("Curiosity", "Mars")
rocket3 = Rocket("Voyager", "Jupiter")

print(rocket1.name, rocket1.destination) # Prints: Apollo, Moon
print(rocket2.name, rocket2.destination) # Prints: Curiosity, Mars
print(rocket3.name, rocket3.destination) # Prints: Voyager, Jupiter

Each rocket possesses distinct attributes, demonstrating the power of __init__.

Constructors automate the initialization process, ensuring uniform attributes across all objects. They enhance coding efficiency and reduce the risk of errors in your code.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal