Concepts / Initializing Objects with __init__

Initializing Objects with __init__

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

  • Programming

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.

createscreatesBankAccount classblueprintAccount Abalance: 500Account Bbalance: 2000
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.

use blueprintcallssets upClass definitionblueprint existsObject creationnew instance__init__runs automaticallyInitial attributesobject state
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

__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.

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

Following self

Two Independent Student Objects

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

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.

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.

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.

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

self.nameself.nameselffirst StudentnameMinaselfsecond StudentnameOmar
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.

containsprovidesoperates onBankAccount objectone organized unitAttributesaccount number, owner,balanceMethodsdeposit, withdraw, check
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

  • Treating the class and the object as the same thing

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

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

  • Forgetting that attributes belong to a particular instance

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

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

  • Using __init__ without initializing the object's expected attributes

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

    Fix: Initialize every attribute that the object will use in __init__.

  • Confusing attributes with methods

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

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

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. Identify the class as the blueprint and the two Book values as separate instances.
  2. List the attributes that every Book object should have.
  3. Explain that __init__ runs automatically for each new instance.
  4. Explain how self makes each assignment belong to the particular Book being created.
  5. Check that the describe method uses the attributes of the object that calls it.

Key Takeaways

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

Key Takeaways

  • 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.