Free preview

100 lessons

Python Done Right

Free preview

Python Done Right · 100 lessons

Learn Python from scratch - syntax through to OOP

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

Our content is best on a larger screen

The __init__() method

What is __init__()?

Explanation

In Python, __init__() is a special method that belongs to a class. It is called automatically every time we create a new instance of that class. The double underscores mark it as a special method that Python recognises and handles automatically - in this case, Python runs __init__() immediately after a new object is created.

We define __init__() inside a class using the def keyword, just like a regular function. The first parameter is always self, which refers to the instance being created (we will explore self in more detail shortly).

class Dog:
    def __init__(self):
        print("A new Dog instance has been created.")

my_dog = Dog()

The message is printed as soon as my_dog is created, because Python automatically calls __init__() after constructing the new Dog object.

If we do not define an __init__() method ourselves, Python provides a default one that does nothing.

Warning

The method must be indented under the class definition, and the body of __init__() must be indented under def __init__(). Incorrect indentation will raise an IndentationError.

Practice questions

3 questions

In the Python Editor, create a class named Agent. In the initialisation method, print the exact phrase: "Agent initialised".

Do not add any other print() statements to your code.

Once done, running the code will output a token used to verify your implementation - what is the token?

Select the correct answer:

+ 2 more questions

Passing arguments to __init__()

Explanation

We can customise how instances are created by adding parameters to __init__() after self. Although self must always be the first parameter, we do not pass it ourselves - Python passes it automatically when we create an instance.

For example, here __init__() accepts a single parameter and calls len() on it:

class WordLength:
    def __init__(self, word):
        print(len(word))

w = WordLength("hello")

When we create the instance with WordLength("hello"), the string "hello" is passed to word, and print(len(word)) outputs 5.

We can use any valid expression or function call with these parameters inside __init__(). We can also accept multiple parameters.

Example

We can define a class called Adder which prints the sum of two numbers each time we create an instance of a class.

class Adder:
    def __init__(self, a, b):
        print(a + b)

where we specified two parameters, a and b (which we can name however we please), after the self parameter.

We can then create a new instance of the Adder class as:

adder = Adder(3, 5)

which will print the value of 8.

Note that the variable adder references an instance of the Adder class - it does not hold the value 8.

Practice questions

3 questions

In the Python Editor, define a class named TextLength. Its __init__() method should accept a single argument (not including self) and print the length of the string passed to it when an instance is created. Do not print anything else in your final code.

Once done, running the code will output the length of some example strings - what is the total length?

Select the correct answer:

+ 2 more questions

The role of self

Explanation

When we define a method inside a class - such as __init__() - the first parameter must refer to the specific instance being created. By convention, we call this parameter self.

When we call something like Dog(), Python creates a new object and automatically passes it in as self. We never pass self ourselves (e.g. writing Dog(self) would be incorrect) - Python handles this behind the scenes.

Even if we do not use self in the method body, we must still include it as the first parameter. In a later lesson, we will use self to store data on each object using instance attributes. For now, the key point is: every instance method must include self as the first parameter.

Info

The name self is not a keyword in Python - it is a naming convention. We should always use it as the first parameter name in instance methods such as __init__().

Example

Consider the following code (enter and run in the Python Editor if you wish):

class Dog:
    def __init__(self):
        print("Inside __init__:", id(self))

dog_1 = Dog()
print("Outside __init__:", id(dog_1))

What do you notice about the IDs that are printed? What does this tell us about self?

Recall

Tip

The built-in id() function returns the unique identifier of an object, which usually corresponds to its memory address during the program's execution.

When we run this code, we see the same ID printed twice - once inside __init__ and once afterwards:

Inside __init__: 19605312
Outside __init__: 19605312

The exact number will differ each time, but the two IDs always match. This confirms that self inside __init__ refers to the same object as the variable (dog_1) we assign the instance to.

Practice questions

3 questions

In the method def __init__(self, name), what does self refer to?

Select the correct answer:

+ 2 more questions