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:
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:
What will be the output?
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__:
What will be the output?
Default parameter values work inside __init__ too. You learned this pattern in Functions I.
If no color is passed, the default is used:
What will be the output?
You can also compute new attributes from the parameters. The body of __init__ is regular Python code.
This Rectangle computes its area during creation:
What will be the output?
What will be the output?
What will be the output?