Classes and OOP I

The __init__ Method

In the previous lesson you added attributes by hand after creating an object. The __init__ method lets you set them up automatically every time a new instance is created.


In the previous lesson you attached attributes to an object after creating it. That works, but it is easy to forget one. Python has a better way.

The __init__ method runs automatically every time you create a new instance:

Python

The first parameter is always self. It refers to the instance being created. You do not pass it yourself. Python handles that.

When you call Dog("Rex"), Python creates the object and passes it as self:

Python
Output

What will be the output?

Python

You can have multiple parameters, just like regular functions. Remember parameters from the Functions I series? Same rules apply here.

A class with two parameters in __init__:

Python
Output

What will be the output?

Python

Default parameter values work inside __init__ too. You learned this pattern in Functions I.

If no color is passed, the default is used:

Python
Output

What will be the output?

Python

You can also compute new attributes from the parameters. The body of __init__ is regular Python code.

This Rectangle computes its area during creation:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python