Lesson 05
Constructors — __init__, Default and Parameterized
Initialize a Python object with __init__, compare default and parameterized constructors, and use default arguments when you need both.
A constructor initializes the object so it does not start empty. In Python that method is always named __init__, and you do not call it yourself.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- What initialization means
- The rules of
__init__ - Default constructors and parameterized constructors
- Why one class keeps a single
__init__
The picture
Initializing means placing the starting data into the object at creation time.
def __init__(self, m, p):
self.label = m
self.seats = pRules:
- The name is always
__init__. - The PVM calls it automatically when the object is created.
- It does not return a useful value. Returning anything other than
NoneraisesTypeError. - A child class can inherit it, and a child class can override it.
- Per object, it runs once: at creation. A normal method can run many times.
There are two forms.
| Form | Signature | Use it when |
|---|---|---|
| Default (parameter-less) | __init__(self) |
Every object should start with the same values |
| Parameterized | __init__(self, m, p) |
Each object should start with different values |
If you write two __init__ methods, the later one replaces the earlier one. Python keeps one constructor per class. To allow both Badge() and Badge("Avery Lane", 4), give the parameters default values:
def __init__(self, m="Guest", p=1):A method can have any name and runs only when you call it. A constructor runs because the object was created, and its job is to set instance fields.
Example
class Badge:
def __init__(self, m="Guest", p=1):
self.label = m
self.seats = p
guest = Badge()
named = Badge("Avery Lane", 4)
print(guest.label, guest.seats)
print(named.label, named.seats)guest uses both defaults. named passes a label and a seat count. The playground prints both lines. There is still only one __init__.
Key takeaways
-
__init__initializes the object during creation -
You do not call it by name; the object call does
-
A default constructor takes only
self -
A parameterized constructor takes values after
self -
Default arguments let one
__init__cover both calling styles -
Next: Destructors — what happens when the object is finished
-
Previous: Objects
Loading playground…
Check your understanding
Constructors quiz
A constructor's job is to:
1 / 10