Concept
The `__init__` Constructor and `self`
`__init__` runs automatically when an instance is created. `self` refers to the specific instance being initialized, attaching unique data to it.
python
class Drone:
def __init__(self, model):
self.model = model
d = Drone("X-100")
print(d.model) # X-100
# 117. The `__init__` Constructor and `self` `__init__` runs automatically when an instance is created. `self` refers to the specific instance being initialized, attaching unique data to it: ```python class Drone: def __init__(self, model): self.model = model d = Drone("X-100") print(d.model) # X-100 ``` Notice you never pass `self` manually when instantiating `Drone("X-100")`. Python automatically passes the freshly allocated memory object as the first argument behind the scenes.
Checkpoint
What does `self` represent inside `__init__(self, ...)`?
Practice
Create a class `User` with an `__init__(self, username, level)` that sets `self.username` and `self.level`. Instantiate `u = User("Ada", 99)` and print `f"{u.username}:{u.level}"`.
01
Tap code blocks below to assemble
Available Blocks