2. Init method
__init__ is a special method that Python calls automatically when an instance is created. It prepares the new object and is often called the constructor:
- The name has two underscores on each side:
__init__(read "dunder init"). selfis the first parameter. It receives the instance being created; Python fills it in, so you never pass it yourself.- The body runs once for every
Dog()call. __init__must not return a value; returning something other thanNoneis an error.
Parameters written after self are the arguments you pass between the parentheses when creating the instance:
- In the definition there are two parameters:
selfandname. - In the call you pass only
name, soDog("Rex")has one argument.selfis automatic.
Coming from JavaScript? __init__ is the constructor. self plays the role of this, but it is written explicitly as the first parameter.
Run code on creation
__init__ runs automatically when you call the class. Define a class Cat with an __init__ method that takes only self and prints A cat is born. Create cat = Cat().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Receive an argument
Define a class Dog whose __init__ has two parameters, self and name, and prints <name> is ready. Create one instance with Dog("Rex"). Remember: self is not an argument in the call.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Two arguments
Define a class Point whose __init__ takes self, x and y, and prints Point at <x>, <y>. Create one point with Point(1, 2).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Each instance gets its own arguments
Define a class Box whose __init__ takes self and label, and prints Box: <label>. Create two boxes, one after the other: Box("small") and Box("large").
Print exactly:
Create a free account to save your progress and unlock chapter 2.