Skip to main content
Albero Academy

Objects & Instances

Create and use instances, and understand class vs instance attributes.

Object-Oriented Programming9 min

An object is a concrete instance created from a class. You can make many objects from one class, and each carries its own state. Understanding the difference between what's shared (class attributes) and what's per-object (instance attributes) is key.

Many objects, one class

Each instance has independent instance attributes; a class attribute is shared by every instance:

instance vs class attributes
class Circle:
pi = 3.14159 # class attribute — shared by ALL circles
def __init__(self, r):
self.r = r # instance attribute — unique per circle
def area(self):
return Circle.pi * self.r ** 2
a = Circle(2)
b = Circle(5)
a.area() # 12.566… uses a's r
b.area() # 78.539… uses b's r
a.r, b.r # (2, 5) independent state

Identity

Each object is distinct in memory. == compares values (if defined); is checks whether two names point at the same object:

two objects are not the same
c1 = Circle(2)
c2 = Circle(2)
c1 is c2 # False — different objects, even with the same radius
c1 is c1 # True

Key takeaways

  1. 01An object is an instance of a class with its own independent state.
  2. 02Instance attributes (self.x) are per-object; class attributes are shared by all.
  3. 03Create instances by calling the class like a function.
  4. 04is checks identity (same object); == checks value equality.
  5. 05Avoid mutable class attributes — they are shared across every instance.

Finished this chapter?

Mark it complete to track your progress through Python.