Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate25 min
Constructors hero Module 17 Lesson 5 init default and parameterized

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

Object creation calls init for you

Initializing means placing the starting data into the object at creation time.

text
def __init__(self, m, p):
    self.label = m
    self.seats = p

Rules:

  1. The name is always __init__.
  2. The PVM calls it automatically when the object is created.
  3. It does not return a useful value. Returning anything other than None raises TypeError.
  4. A child class can inherit it, and a child class can override it.
  5. 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:

text
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

python
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