Skip to content
BENIBIX Learn

Constructor

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as __init__, Constructor Method, Initializer

A method that runs when a new object is made. It sets the first values.

Think of it like

Think of it like a name tag. You fill it in the day a new pet comes home.

Example

When Emma writes Dog("Rex"), the constructor runs and saves Rex as the dog's name.

Why it matters

It makes sure every object starts in a valid state. No dog exists without a name.

Definition

A constructor is a special method that runs once, when a new object is made. Its job is to set up the object's first values, like a name or a score of zero. In Python it is called __init__; in JavaScript and Java it is called constructor. Whatever you pass when you make the object goes to it. Without one, the object starts with nothing set.

Example code

python
class Dog:
    def __init__(self, name):
        self.name = name
__init__ runs once for each new dog and stores its name.

Common mistake

Doing slow work, like reading files, inside the constructor. Making each object then becomes slow.

Key takeaways

  1. 1
    Runs once. When the object is made.
  2. 2
    Sets starting values. From what you pass in.
  3. 3
    Different names. __init__ or constructor.