Concepts / Initializing Objects with __init__

Initializing Objects with __init__

An object bundles data (attributes) and behavior (methods) into a single, organized unit.

  • Programming
Interactive lab

Try it: Classes, Instances and Attributes

How a class creates instances with __init__ and self, why an attribute read checks the instance's __dict__ before the class, why assigning through an instance never changes the class, how a class-level list is shared by every instance, and why obj.method(x) is Class.method(obj, x).

How it works

  1. Dog(...) makes a new, empty instance and calls Dog.__init__(new_object, ...); self.name = ... stores into that object's __dict__.
  2. Reading obj.attr looks in obj.__dict__ first, then in the class.
  3. Assigning obj.attr = value always writes obj.__dict__, so it shadows a class attribute for that one object only.
  4. Mutating a class-level list (self.tricks.append) changes the one list every instance shares.
  5. obj.method is found on the class and bound to obj, so obj.method(x) runs Class.method(obj, x).

Default run (30 steps): Ready: class Dog and the statements you picked. Watch where each attribute is found and where each assignment writes. … Finished. Printed: ['sit'] / Wolf / Canis familiaris / Fido is 5.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. Object numbers are illustrative, not real id() values.

Educational simulation

Loading the simulation…

From Blueprint to Object

Imagine tracking several bank accounts. Each account needs data such as an account number, an owner's name, and a balance. It also needs actions such as depositing, withdrawing, and checking the balance. A class groups this related data and behavior into one organized structure. The class is the blueprint; each bank account created from it is an object, or instance. The important question for this article is how each new object receives its starting data.

BankAccount classblueprintAccount Abalance: 500Account Bbalance: 2000createscreates
What does the class define, and what does each object contain?

The Creation Sequence

Object creation can be understood as a sequence. First, the class provides the blueprint. Next, a program creates an instance from that class. During that creation, __init__ runs automatically. Its purpose is to initialize the object's attributes with starting values. After this step, the instance has the data it needs for its initial state and can use the behavior defined by the class.

Class definitionblueprint existsObject creationnew instance__init__runs automaticallyInitial attributesobject stateuse blueprintcallssets up
What happens in what order when a class becomes an initialized object?

What do you think happens?

A class is used to create two account objects. Will one object's starting balance automatically become the other object's starting balance?

  • Yes, all instances share one balance

  • No, each instance receives its own initialized attributes

Reveal answer
Answer:

No, each instance receives its own initialized attributes.

The source describes each instance as having its own separate set of attributes. Each object's attributes are initialized by its own call to __init__, so instances can have different data while following the same class blueprint.

Writing Initial State

Definition

__init__ is a special method that runs automatically when an object is instantiated. It initializes the object's attributes and marks the beginning of the object's lifecycle.

An attribute is data that belongs to an object. For a Student object, attributes might include name, student_id, and gpa. A method is a function that belongs to the object's behavior. For example, a method might calculate a letter grade or update the gpa. The class keyword places these related attributes and methods inside one cohesive blueprint. The __init__ method is the part that gives each newly created object its initial attribute values.

python

In this example, Student is the class and student is one instance. When the instance is created, __init__ runs and assigns three attributes. The assignments use self to attach each value to the particular object being created. The update_gpa method later operates on that object's gpa attribute. A second Student object could be created with different values and would receive its own separate attributes.

Student instancebeing createdStudent instancename, student_id, gpa__init__ assigns attributes
How does __init__ change an instance from a newly created object into one containing specific data?

Following self

Worked example

Two Independent Student Objects

Trace what happens when two Student objects are created from the same class.

  1. 1
    Create the first instance

    The first call creates a Student object and automatically runs __init__. During this call, self refers to that particular object, so the name, student_id, and gpa assignments belong to the first instance.

  2. 2
    Create the second instance

    The second call creates another Student object and runs __init__ again. This time, self refers to the second object, so its attributes are initialized separately.

  3. 3
    Use a method

    If update_gpa is called on one student, the method operates on the gpa attribute connected to the object that called it.

Result

Both objects follow the Student blueprint and have the same available behavior, but each has its own attribute values.

selffirst StudentnameMinaselfsecond StudentnameOmarself.nameself.name
How does self connect an assignment in __init__ to the particular object being created?

Data and Behavior Together

An object bundles data and behavior into one organized unit. Attributes store information about the object's state or characteristics. Methods perform actions and typically work with those attributes. This relationship keeps an action close to the data it uses. In a bank account, for example, the balance is data, while depositing, withdrawing, and checking the balance are behaviors associated with that account.

BankAccount objectone organized unitAttributesaccount number, owner,balanceMethodsdeposit, withdraw, checkcontainsprovidesoperates on
How are an object's stored data and the methods that operate on it organized together?
python

The BankAccount class organizes the account data and actions together. When the account is created, __init__ establishes the initial account number, owner, and balance. When deposit is called, self identifies which account's balance should be changed. A different BankAccount object could use the same method while keeping its own independent balance.

Mistakes with Initialization

  • Common mistake

    Treating the class and the object as the same thing

    What it looks like

    Thinking that BankAccount is one specific account rather than the blueprint for account objects.

    Why it fails

    The class defines the structure and behavior, while each object is an instance created from that blueprint.

    Do this instead

    Ask whether you are describing the plan or one individual instance.

  • Common mistake

    Forgetting that attributes belong to a particular instance

    What it looks like

    Assuming that two Student objects must have the same name or gpa because they came from the same class.

    Why it fails

    Each instance has its own separate set of attributes and can have different values.

    Do this instead

    Trace self in each call to __init__; it refers to the specific object being initialized.

  • Common mistake

    Using __init__ without initializing the object's expected attributes

    What it looks like

    Creating a class whose objects later use balance, but never assigning an initial balance in __init__.

    Why it fails

    The object may not begin in a valid, predictable state.

    Do this instead

    Initialize every attribute that the object will use in __init__.

  • Common mistake

    Confusing attributes with methods

    What it looks like

    Describing balance as an action or deposit as stored data.

    Why it fails

    Attributes store information, while methods perform actions, usually using the object's attributes.

    Do this instead

    Classify each class member by asking whether it stores state or performs behavior.

Best practice

When reading or writing a class, trace the lifecycle in order: identify the blueprint, identify the instance being created, find the automatic call to __init__, and list the attributes that __init__ assigns through self. This makes it easier to predict the object's starting state and to see which data a method can use.

Practice the Trace

MEDIUM

Write a Python class named Book with an __init__ method that initializes title and author. Then add a method named describe that operates on the book's attributes. Create two Book objects with different values and explain why their title and author data remain independent.

Hints
  • Use the class keyword followed by Book.
  • The __init__ method should receive self, title, and author.
  • Attach the values to the object with self.title and self.author.
  • For the two objects, trace which object self refers to during each call.
  1. 1
    Identify the class as the blueprint and the two Book values as separate instances.
  2. 2
    List the attributes that every Book object should have.
  3. 3
    Explain that __init__ runs automatically for each new instance.
  4. 4
    Explain how self makes each assignment belong to the particular Book being created.
  5. 5
    Check that the describe method uses the attributes of the object that calls it.

Key Takeaways

  1. 1
    A class is a blueprint, while an object is an instance created from that blueprint.
  2. 2
    Attributes store an object's information, and methods perform actions involving that information.
  3. 3
    The class keyword groups related data and behavior into a cohesive structure.
  4. 4
    __init__ runs automatically when an object is instantiated and establishes its initial state.
  5. 5
    self refers to the particular object being initialized, so each instance receives its own independent attributes.

At a glance

  • A class defines a reusable blueprint for related data and behavior.
  • Each object created from a class is an independent instance with its own attributes.
  • __init__ runs automatically during instantiation to establish the object's initial state.
  • The self parameter connects attribute assignments and method actions to the specific instance.
  • Initializing all attributes in __init__ helps every object begin in a valid, predictable state.

Related concepts

More concepts starting with I