Editor settings

General settings

Save settings

Learn to program with Python

Special method __init__ #

We can create a method for a class by defining a function inside the class body. A method is a function defined within a class that can be called just like a regular function.

For example:

class Car:
    def method_name(self):
        print("The method method_name is called")

car = Car()
car.method_name() # Output: The method method_name is called
The first parameter of a class method is always the object itself, which is conventionally named self. This value is automatically passed to the method whenever it is called, and we do not need to pass it ourselves.

In the example above, the self value will be the object car.

What is the __init__ method #

The __init__ method in Python is a special method, also known as the constructor method, which gets automatically called when an object is created from a class.

For example, if we update the Car class to have the __init__ method, like so:

class Car
    def __init__(self):
        print("A new car object is created")

car = Car() # Output: A new car is created
car2 = Car() # Output: A new car is created

Whenever we create a new car object with Car(), the method __init__ is then called. In this case, the message "A new car object is created" is then printed in the output.


Exercise #

  • Create an __init__ method inside out Person class that prints out a message whenever an object is created from the Person class. Then try creating an object from the Person class.

Tests #

  • The message "A new person is created" should be printed when a new Person object is created
  • Variable new_person should be a Person object
Output will be displayed here