Concepts / Understanding Attributes and Methods

Understanding Attributes and Methods

The important chain is class definition, object creation, automatic initialization, method call, and attribute update. The class supplies the structure, __init__ establishes the starting data, and self ensures that later methods use the correct object's data.

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

A Template Is Not an Object

When you first see the class keyword, it is natural to think that an object has already been created. Python separates these two ideas. A class is a template that defines the data and code objects of that type will have. The class keyword defines the template; it does not create an object. An object is created later by calling the class as if it were a function.

PartyAnimalclass templateanobject instanceanother objectindependent instancecalled to createcalled to create
What does the class definition provide, and what happens when the class is called?

Tracing Object Creation

What do you think happens?

After the class has been defined, what does the statement an = PartyAnimal() do?

  • It only gives a name to the class template

  • It creates an object and runs its initializer

  • It changes an existing object's attribute

Reveal answer
Answer:

It creates a new PartyAnimal object and automatically runs its __init__ method.

Objects are created by calling the class as if it were a function. During that creation, __init__ runs and sets up the object's initial attributes.

  1. 1
    Python first has the PartyAnimal class definition available as a template.
  2. 2
    The call PartyAnimal() creates a new object.
  3. 3
    Python automatically runs that object's __init__ method.
  4. 4
    The __init__ method gives the object its initial attribute values.
  5. 5
    The name an refers to the newly created object.
PartyAnimal()class callnew objectinstance__init__initializerx0createsruns automaticallysets
What happens to a new object from the class call through its initial attribute assignment?

Attributes and Initialization

Definition

An attribute is data associated with an object. The __init__ method runs automatically when an object is created and sets up the object's initial attributes. This gives every new object an initialized starting state.

python

In this example, the class definition describes a kind of object. The __init__ method establishes an attribute named x, and the initial value assigned to that attribute is 0. The expression self.x refers to the x attribute belonging to the particular object being initialized.

How self Chooses the Object

Definition

The self parameter in a method refers to the specific object instance on which that method was called. It allows the method to access and modify that object's attributes.

The same class can produce many objects. Each object has its own independent data. When a method is called through one object, self connects the method to that object, so an expression such as self.x reads or changes the correct object's x attribute rather than the attribute belonging to a different object.

anx = 0an.party()method callselfanxobject datainvokesbinds toaccesses
How does a method call connect to the particular object whose attributes it reads or changes?

Methods Change Object Data

Code walkthrough
class PartyAnimal:
    def __init__(self):
        self.x = 0

    def party(self):
        self.x = self.x + 1
        print(self.x)

an = PartyAnimal()
an.party()
an.party()
an.party()
  1. 1
    PartyAnimal() creates an object and runs __init__, so an.x starts at 0.
  2. 2
    The first an.party() call uses self to refer to an, changes x from 0 to 1, and prints 1.
  3. 3
    The second call changes x from 1 to 2 and prints 2.
  4. 4
    The third call changes x from 2 to 3 and prints 3.
  • The class defines the structure and behavior for PartyAnimal objects.
  • The initializer gives each new object an x attribute with value 0.
  • The party method uses self to find the calling object's x attribute.
  • Each call adds 1 to that object's x value and prints the new value.
  • The three calls produce the values 1, 2, and 3.
Output
1
2
3
x = 0after initializationx = 1after first party callx = 2after second party callx = 3after third party callparty()party()party()
How does calling party change the stored attribute value on the same object?

A method is code associated with a class that can operate on an object. In this example, party uses self.x both to read the current value and to store the updated value. Because self refers to an, every call changes an's own attribute.

A Complete Execution Trace

Worked example

Following one PartyAnimal object

Trace the object named an from creation through three calls to party.

  1. 1
    Define the class

    The PartyAnimal class becomes a template describing the data and methods its objects will have. No PartyAnimal object has been created merely by defining the class.

  2. 2
    Create the object

    The call PartyAnimal() creates a new object. Python automatically runs __init__ for that object.

  3. 3
    Initialize the attribute

    The initializer sets the object's x attribute to 0, so an begins with x equal to 0.

  4. 4
    Call party three times

    Each call binds self to an, increases an.x by 1, and prints the new value.

Result

The object starts with x equal to 0. After three party calls, x is 3, and the printed values are 1, 2, and 3.

Key point

The important chain is class definition, object creation, automatic initialization, method call, and attribute update. The class supplies the structure, __init__ establishes the starting data, and self ensures that later methods use the correct object's data.

Mistakes Beginners Make

  • Common mistake

    Assuming that writing class creates an object

    What it looks like

    Defining PartyAnimal is treated as though an instance already exists.

    Why it fails

    The class keyword defines a template. An object is created only when the class is called.

    Do this instead

    Separate the class definition from the later call that creates an object, such as PartyAnimal().

  • Common mistake

    Treating __init__ as an ordinary method that must be called manually

    What it looks like

    The initialization step is ignored after an object is created.

    Why it fails

    __init__ runs automatically when the object is created and sets up its initial attributes.

    Do this instead

    Recognize object creation as the event that automatically invokes __init__.

  • Common mistake

    Forgetting that self identifies the current object

    What it looks like

    A method changes an attribute without connecting the operation to the object on which the method was called.

    Why it fails

    Methods need self to access and modify the attributes of the specific instance using the method.

    Do this instead

    Use self when referring to the current object's attributes, such as self.x.

  • Common mistake

    Expecting every object from a class to share one changing attribute value

    What it looks like

    A change made through one object is assumed to change every object created from the class.

    Why it fails

    Each object has its own independent copy of the attributes defined for it.

    Do this instead

    Track the attribute through the relevant self reference and object instance.

Practice the Object Lifecycle

EASY

Create a simple class based on the PartyAnimal pattern. Give it an __init__ method that sets an attribute to 0, then add a method that uses self to increase that attribute by 1. Describe what happens when an object is created and the method is called twice.

Hints
  • Start by identifying the class template.
  • Put the initial attribute assignment in __init__.
  • Use self when reading and changing the object's attribute.
  • Trace the attribute from its initial value through both method calls.
Key point

To check your reasoning, the object should begin with the value assigned in __init__. Each method call should operate on that same object's attribute through self, so two increments produce a value two greater than the starting value.

Essential Takeaways

  1. 1
    A class is a template for the data and code that its objects will have; defining a class does not create an object.
  2. 2
    Calling a class as if it were a function creates an object instance.
  3. 3
    The __init__ method runs automatically during object creation and establishes the object's initial attributes.
  4. 4
    The self parameter refers to the particular object using a method.
  5. 5
    Methods use self to read and modify that object's independent attributes.
  6. 6
    One class can create many objects, each with its own data.

At a glance

  • A class defines a reusable template, while an object is an instance created from that template.
  • Calling the class creates an object and automatically runs its __init__ method.
  • The __init__ method establishes the object's initial attributes.
  • The self parameter connects each method call to the specific object whose data the method reads or changes.
  • Methods can update an object's attributes, and each object maintains its own independent data.

Related concepts

More concepts starting with U