Skip to content
Laviyx Learn

Try

Python course menu

Python Objects: Instances, Attributes, Identity and Everything Is an Object

Learn how Python objects work: create independent instances, read and change attributes, add attributes dynamically, hasattr and getattr, object identity vs equality, defining __eq__, and storing objects in lists.

Intermediate7 min readUpdated
On this page

A class is a blueprint; an object is a real thing built from it. In this lesson you will work with objects directly: creating several, changing them independently, comparing them, and collecting them in lists, the way real programs use them.

Each object has its own data#

Python
class Student:
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores

    def average(self):
        return sum(self.scores) / len(self.scores)

a = Student("Asha", [92, 88, 95])
b = Student("Ravi", [70, 85, 80])

print(a.average(), round(b.average(), 1))

a.scores.append(100)
print(a.scores, b.scores)
Output
91.66666666666667 78.3
[92, 88, 95, 100] [70, 85, 80]

a and b are separate instances of Student. Changing Asha's scores does not touch Ravi's.

Attributes are flexible#

Python lets you add attributes to an object at any time, and inspect them:

Python
class Student:
    def __init__(self, name):
        self.name = name

s = Student("Asha")
s.city = "Pune"                      # added after creation
print(s.city, s.__dict__)
print(hasattr(s, "city"), getattr(s, "age", "unknown"))
Output
Pune {'name': 'Asha', 'city': 'Pune'}
True unknown
  • __dict__ shows an object's attributes as a dictionary.
  • hasattr(obj, "name") checks whether an attribute exists.
  • getattr(obj, "name", default) reads an attribute by name, with a fallback.

Identity vs equality#

Two objects with the same data are still different objects:

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

p1 = Point(1, 2)
p2 = Point(1, 2)
p3 = p1

print(p1 == p2, p1 is p3)
p3.x = 99
print(p1.x)
Output
False True
99
  • p1 == p2 is False: by default, == on objects checks identity, just like is.
  • p3 = p1 does not copy the object; both names refer to the same object, so changing p3.x changes p1.x.

Define __eq__ to compare by value instead:

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)

print(Point(1, 2) == Point(1, 2))
Output
True

Collections of objects#

Objects shine when you work with many of them. Sort or search by any attribute with a lambda:

Python
class Student:
    def __init__(self, name, score):
        self.name, self.score = name, score

students = [Student(n, s) for n, s in [("Asha", 92), ("Ravi", 85), ("Meera", 97)]]

top = max(students, key=lambda s: s.score)
print(top.name, [s.name for s in sorted(students, key=lambda s: s.score)])
Output
Meera ['Ravi', 'Asha', 'Meera']

Everything in Python is an object#

Numbers, strings, lists, functions, even classes themselves are objects, with a type and methods:

Python
print(isinstance(5, int), isinstance("hi", str), type([]).__name__)
print((5).bit_length(), "hi".upper())
Output
True True list
3 HI

That is why "hi".upper() works: "hi" is an instance of the str class, and upper is one of its methods.

Common mistakes#

Practice#

Practice exercise

Write a Cart class whose items attribute is a dictionary of {name: {"price": ..., "qty": ...}}. Give it an add(name, price, qty=1) method that increases the quantity if the item is already in the cart, and a total() method. Add 3 notebooks at ₹60, 1 pen at ₹20, then 1 more notebook, and print the notebook quantity and the total.

Show hint

In add, check if name in self.items: and increase qty; otherwise create a new entry. total() sums price * qty.

Show solution
Python
class Cart:
    def __init__(self):
        self.items = {}

    def add(self, name, price, qty=1):
        if name in self.items:
            self.items[name]["qty"] += qty
        else:
            self.items[name] = {"price": price, "qty": qty}

    def total(self):
        return sum(i["price"] * i["qty"] for i in self.items.values())

cart = Cart()
cart.add("Notebook", 60, 3)
cart.add("Pen", 20)
cart.add("Notebook", 60)
print(cart.items["Notebook"]["qty"], cart.total())
Output
4 260

4 notebooks × 60 + 1 pen × 20 = 260.

Key takeaway#

Finished this lesson?