Python course · Module 8: OOP in Python · Lesson 38 of 63
Quick answer: A Python class is a blueprint for objects. You write class ShoppingCart: and inside it an __init__(self, ...) method that gives each new object its starting data, such as self.owner = owner. Calling ShoppingCart("Amna") creates an object (an instance) with its own attributes, and methods like cart.total() are functions that work on that object through self. Python classes keep data and the code that uses it together in one place.
In this lesson you will learn:
- what classes and objects are, and how to create objects
- how
__init__andselfset up the attributes of each object - how to write and call methods
- the difference between instance and class attributes, and the shared list trap
- how
__str__and__repr__make objects print nicely, in a small shopping cart class
Before you start: finish Lesson 37, Python Debugging and Logging: breakpoint(), pdb and the logging Module. You need functions from Lesson 22 and dictionaries from Lesson 17. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org, apart from two lines that we point out.
Table of Contents
What are Python classes and objects?
You have used objects since the first lessons. Every list and every string is an object, and its type is a class:
prices = [1.5, 3.0]
name = "notebook"
print(type(prices), type(name))
prices.append(20.0)
print(prices)
print(name.upper())
<class 'list'> <class 'str'>
[1.5, 3.0, 20.0]
NOTEBOOK
prices is an object of the class list, and name an object of the class str. Each object holds its own data (the values) and has methods, functions that belong to it, like append() and upper().
The Python tutorial says: “Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object.” A class is the plan, and objects (also called instances) are the things built from it. One ShoppingCart class can make a cart for every customer.
Create a class and objects
The smallest class has a name and an empty body:
class ShoppingCart:
pass
cart = ShoppingCart()
other = ShoppingCart()
print(type(cart))
print(cart)
print(cart is other)
<class '__main__.ShoppingCart'>
<__main__.ShoppingCart object at 0x7fc8888986e0>
False
class ShoppingCart:defines a new class. PEP 8 says class names “should normally use the CapWords convention”:ShoppingCart, notshopping_cart.ShoppingCart()calls the class like a function. Each call makes a new object.type(cart)shows the new class;__main__means it was defined in the file we ran.print(cart)shows the class and a memory address. The number changed between our runs, and yours will differ. We make this output readable later.cart is otherisFalse: two calls make two separate objects (Lesson 9 explainsis).
You already wrote small classes in Lesson 36, when you defined your own exceptions. Now we write classes that hold data.
__init__ and self: give each object its data
A cart needs an owner and a place for its items. __init__ is a special method that runs automatically when you create an object. The tutorial says “class instantiation automatically invokes __init__()” for the new instance:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
amna = ShoppingCart("Amna")
bilal = ShoppingCart("Bilal")
print(amna.owner, amna.items)
print(bilal.owner, bilal.items)
amna.items["pen"] = (1.5, 4)
amna.owner = "Amna Khan"
print(amna.owner, amna.items)
print(bilal.owner, bilal.items)
Amna {}
Bilal {}
Amna Khan {'pen': (1.5, 4)}
Bilal {}
ShoppingCart("Amna")creates a new object, then calls__init__with it asselfand"Amna"asowner.selfis the object being set up.self.owner = ownerstores the value on that object. Values stored like this are called attributes.- You read and change attributes with a dot:
amna.owner,amna.items["pen"] = (1.5, 4). - Changing Amna’s cart did not change Bilal’s. Each object has its own
itemsdictionary.
self is only a name. The tutorial calls it “nothing more than a convention”, but PEP 8 says: “Always use self for the first argument to instance methods.”
Methods: functions that belong to a class
A method is a function written inside the class. Its first parameter is self, so it can use the object’s attributes:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
cart = ShoppingCart("Amna")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print(cart.items)
print("Total:", cart.total())
print("Same call:", ShoppingCart.total(cart))
{'pen': (1.5, 4), 'notebook': (3.0, 1)}
Total: 9.0
Same call: 9.0
add_item()stores each item as a(price, quantity)tuple.quantity=1is a default value, as in Lesson 23.total()multiplies price by quantity for every item: 4 × 1.5 + 1 × 3.0 = 9.0. Thesum(... for ...)form is from Lesson 21.- You call a method on the object:
cart.total(). You do not passself; Python does it. The tutorial saysx.f()“is exactly equivalent toMyClass.f(x)“, which is whyShoppingCart.total(cart)gives the same 9.0.
Instance attributes vs class attributes
Attributes made with self.name = ... are instance attributes: each object has its own. Attributes written directly in the class body are class attributes: one value, shared by all objects of the class. The tutorial puts it this way: “instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances”.
class ShoppingCart:
currency = "USD"
def __init__(self, owner):
self.owner = owner
self.items = {}
amna = ShoppingCart("Amna")
bilal = ShoppingCart("Bilal")
print(amna.currency, bilal.currency, ShoppingCart.currency)
ShoppingCart.currency = "EUR"
print(amna.currency, bilal.currency)
bilal.currency = "PKR"
print(amna.currency, bilal.currency, ShoppingCart.currency)
print(vars(amna))
print(vars(bilal))
USD USD USD
EUR EUR
EUR PKR EUR
{'owner': 'Amna', 'items': {}}
{'owner': 'Bilal', 'items': {}, 'currency': 'PKR'}

- First, both carts read
currencyfrom the class:USD. - Changing
ShoppingCart.currencychanged it for every cart at once, because they share it. bilal.currency = "PKR"did not change the class. It created a new instance attribute on Bilal’s cart only, which hides the class value for him.vars()shows an object’s own attributes as a dictionary. Only Bilal’s hascurrency; Amna’s cart still uses the class one.
The shared list trap
Class attributes are fine for fixed values like currency. They are dangerous for lists and dictionaries. The tutorial warns that shared data “can have possibly surprising effects involving mutable objects such as lists and dictionaries”:
class ShoppingCart:
items = []
def __init__(self, owner):
self.owner = owner
def add_item(self, name):
self.items.append(name)
amna = ShoppingCart("Amna")
bilal = ShoppingCart("Bilal")
amna.add_item("pen")
bilal.add_item("bag")
print("Amna:", amna.items)
print("Bilal:", bilal.items)
print(amna.items is bilal.items)
Amna: ['pen', 'bag']
Bilal: ['pen', 'bag']
True
There is only one items list, stored on the class, so both customers see both items. amna.items is bilal.items is True. self.items.append() changes that shared list; it does not create a new one. This is the same idea as the mutable default argument trap from Lesson 23. The fix: create the list in __init__ with self.items = [], so every object gets its own new list.
__str__ and __repr__: print objects nicely
<__main__.ShoppingCart object at 0x...> is not helpful. Two special methods control how an object turns into text:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def __str__(self):
return f"{self.owner}'s cart with {len(self.items)} items"
def __repr__(self):
return f"ShoppingCart({self.owner!r})"
cart = ShoppingCart("Amna")
print(cart)
print(str(cart))
print(repr(cart))
print([cart, ShoppingCart("Bilal")])
Amna's cart with 0 items
Amna's cart with 0 items
ShoppingCart('Amna')
[ShoppingCart('Amna'), ShoppingCart('Bilal')]
__str__is used byprint()andstr(). The data model docs call it the “informal” or nicely printable form. Write it for users.__repr__is used byrepr()and when you print a list that holds the object. The docs say it “is typically used for debugging” and should, if possible, “look like a valid Python expression”.ShoppingCart('Amna')is exactly the code that makes such a cart.- If you write only one, write
__repr__: the docs say it is then also used forstr().
Methods with two underscores on each side are often called “dunder” methods. Lesson 41 covers more of them.
A complete example: a shopping cart class
Here is everything together, plus input checks with raise from Lesson 36 and a receipt with the f-string formats from Lesson 7:
class ShoppingCart:
"""A simple shopping cart: item name -> (price, quantity)."""
currency = "USD"
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
if quantity < 1:
raise ValueError(f"quantity must be at least 1, got {quantity}")
if name in self.items:
old_price, old_quantity = self.items[name]
quantity += old_quantity
self.items[name] = (price, quantity)
def remove_item(self, name):
if name not in self.items:
raise KeyError(f"{name!r} is not in the cart")
del self.items[name]
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def receipt(self):
lines = [f"Receipt for {self.owner}"]
for name, (price, quantity) in self.items.items():
lines.append(f" {name:<10} {quantity} x {price:>5.2f} = {price * quantity:>6.2f}")
lines.append(f" {'Total':<10} {self.total():>17.2f} {self.currency}")
return "\n".join(lines)
def __str__(self):
return f"{self.owner}'s cart with {len(self.items)} items"
def __repr__(self):
return f"ShoppingCart({self.owner!r})"
cart = ShoppingCart("Amna")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
cart.add_item("pen", 1.5, 2)
cart.add_item("bag", 20.0)
cart.remove_item("bag")
print(cart)
print(cart.receipt())
try:
cart.add_item("ruler", 0.75, 0)
except ValueError as err:
print("Error:", err)
Amna's cart with 2 items
Receipt for Amna
pen 6 x 1.50 = 9.00
notebook 1 x 3.00 = 3.00
Total 12.00 USD
Error: quantity must be at least 1, got 0
- Adding
"pen"a second time increased its quantity from 4 to 6 instead of replacing it. remove_item("bag")deleted the bag, so the cart has 2 items and the total is 6 × 1.50 + 3.00 = 12.00.- A quantity of 0 raised
ValueError, and the object stayed unchanged. - The class has a docstring, just like a function.
The data (owner, items) and the actions (add_item, remove_item, total, receipt) live together. Code that uses the cart does not need to know that items are stored as tuples in a dictionary.
Try it yourself
Exercise 1: A Book class
Write a Book class with title, author and pages. Add describe(), which returns a string like "Python Basics by A. Writer, 250 pages", and is_long(), which returns True for more than 300 pages. Make two books and print both results for each.
Exercise 2: A click counter
Write a ClickCounter class whose count starts at 0, with click() (adds 1) and reset() (back to 0). Make two counters, like and share, click like three times and share once, and print both counts. Then reset like.
Exercise 3: Fix the playlist
This class has the shared list trap. Fix it and add a __str__ that returns "Study: 1 songs":
class Playlist:
songs = []
def __init__(self, name):
self.name = name
def add(self, song):
self.songs.append(song)
Solutions
Solution 1
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def describe(self):
return f"{self.title} by {self.author}, {self.pages} pages"
def is_long(self):
return self.pages > 300
books = [Book("Python Basics", "A. Writer", 250), Book("Big Data Book", "B. Author", 520)]
for book in books:
print(book.describe(), "| long:", book.is_long())
Python Basics by A. Writer, 250 pages | long: False
Big Data Book by B. Author, 520 pages | long: True
Each Book object keeps its own title, author and pages, and the methods read them through self.
Solution 2
class ClickCounter:
def __init__(self):
self.count = 0
def click(self):
self.count += 1
def reset(self):
self.count = 0
like = ClickCounter()
share = ClickCounter()
like.click()
like.click()
like.click()
share.click()
print("Likes:", like.count, "| Shares:", share.count)
like.reset()
print("Likes after reset:", like.count)
Likes: 3 | Shares: 1
Likes after reset: 0
self.count += 1 changes only the counter you call it on.
Solution 3
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add(self, song):
self.songs.append(song)
def __str__(self):
return f"{self.name}: {len(self.songs)} songs"
study = Playlist("Study")
gym = Playlist("Gym")
study.add("Rain sounds")
gym.add("Fast beat")
gym.add("Run song")
print(study, study.songs)
print(gym, gym.songs)
Study: 1 songs ['Rain sounds']
Gym: 2 songs ['Fast beat', 'Run song']
self.songs = [] inside __init__ gives each playlist its own list.
Common mistakes
- Forgetting
selfin a method.def total():fails when called ascart.total():TypeError: ShoppingCart.total() takes 0 positional arguments but 1 was given. The “1” is the object Python passes automatically. - Forgetting
self.before an attribute.items[name] = priceinside a method givesNameError: name 'items' is not defined. Did you mean: 'self.items'?. Python even suggests the fix. - Misspelling
__init__. With__int__(or one underscore), Python never runs it, andShoppingCart("Amna")fails withTypeError: ShoppingCart() takes no arguments. - Calling a method on the class.
ShoppingCart.total()givesTypeError: ShoppingCart.total() missing 1 required positional argument: 'self'. Create an object first and callcart.total(). - Returning a number from
__str__. It must return a string. Python 3.14.6 saysTypeError: __str__ returned non-string (type int), and Python 3.15.2 saysTypeError: ShoppingCart.__str__() must return a str, not int.
Frequently asked questions
What is self in Python?
self is the first parameter of every method, and it is the object the method was called on. In cart.total(), Python passes cart as self, so self.items means “this cart’s items”. The name is a convention, but always use it.
What is __init__ in Python?
__init__ is the method Python calls automatically right after it creates a new object. It sets the starting attributes, such as self.owner = owner. It is not required, but almost every class that stores data has one.
What is the difference between a class and an object?
A class is the definition, like a plan: class ShoppingCart:. An object is one thing made from that plan, like ShoppingCart("Amna"). One class can make any number of objects, and each has its own instance attributes.
Summary
- A class (
class ShoppingCart:) is a blueprint; calling it (ShoppingCart("Amna")) creates an object, also called an instance. __init__(self, ...)runs for every new object and stores its data as attributes withself.name = value.- Methods are functions inside the class with
selffirst; call them ascart.total(). - Class attributes are shared by all objects; never use a class-level list or dict for per-object data, create it in
__init__instead. __str__gives a friendly text forprint(), and__repr__a precise one for debugging. Class and static methods and@propertycome in Lesson 39, inheritance in Lesson 40 and dataclasses in Lesson 42.
Next lesson
Next: Lesson 39, Python Instance, Class and Static Methods and @property.
Sources
- Classes (Python tutorial)
- Data model: object.__repr__ and object.__str__ (Python docs)
- PEP 8: Style Guide for Python Code
- Python downloads page (python.org)





