Python Classes/Objects Examples
Short, runnable programs that show python classes and objects in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Classes and Objects lesson.
1A method that protects the data
Methods can check a request before changing an attribute. Here spend refuses to take more cash than the wallet holds and returns whether it worked.
class Wallet:
def __init__(self, cash):
self.cash = cash
def spend(self, amount):
if amount > self.cash:
return False
self.cash -= amount
return True
wallet = Wallet(20)
print(wallet.spend(15), wallet.cash)
print(wallet.spend(15), wallet.cash)Expected outputTrue 5
False 5
2Class attributes vs instance attributes
school and count live on the class and are shared. name is set on self, so each student has their own.
class Student:
school = "Hillside High"
count = 0
def __init__(self, name):
self.name = name
Student.count += 1
a = Student("Asha")
b = Student("Ben")
print(a.name, "|", b.name)
print(a.school, "|", b.school)
print("Students created:", Student.count)Expected outputAsha | Ben
Hillside High | Hillside High
Students created: 2
3__str__ for people, __repr__ for programmers
print() uses __str__. A list shows its items with __repr__, and f-strings can ask for it with !r.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
p = Point(2, 5)
print(p)
print([p, Point(0, 0)])
print(f"Debug: {p!r}")Expected output(2, 5)
[Point(x=2, y=5), Point(x=0, y=0)]
Debug: Point(x=2, y=5)
4A list of objects
Objects fit anywhere other values do. Each Item knows how to calculate its own total, so the loop stays simple.
class Item:
def __init__(self, name, price, qty):
self.name = name
self.price = price
self.qty = qty
def total(self):
return self.price * self.qty
cart = [Item("pen", 1.5, 4), Item("notebook", 3.25, 2), Item("bag", 24.0, 1)]
for item in cart:
print(f"{item.name:<10}{item.total():>6.2f}")
print("Grand total:", sum(item.total() for item in cart))Expected outputpen 6.00
notebook 6.50
bag 24.00
Grand total: 36.5
Practise next
Python Classes and Objects exercises → Back to the lesson
Python Class Attributes vs Instance Attributes examplesPython Encapsulation: Public, Protected and Private examplesPython Dunder (Magic) Methods examples