Python Classes and Objects
1Python Classes/Objects: overview
A class is a blueprint that describes what data a kind of thing holds and what it can do; an object is one concrete thing built from that blueprint, with its own copy of the data.
Before this lesson: Python Dictionaries, Python Functions
2Python Classes/Objects: diagram
3Python Classes/Objects: explained step by step
So far you have kept data in variables, lists and dictionaries, and written functions that work on that data. A class lets you keep the data and the functions that belong to it together, under one name.
Class vs object
Think of a class as a cookie cutter and objects as the cookies. The class BankAccount describes what every account has (an owner and a balance) and what it can do (take a deposit). Each account you create — acct1, acct2 — is a separate object, also called an instance, with its own values.
__init__ and self
When you call a class like a function, BankAccount("Asha", 120), Python creates a new, empty object and immediately runs its __init__ method to set it up. The first parameter, self, is that new object. Writing self.owner = owner stores a value on the object; a value stored like that is called an attribute.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog("Rex", 3)
bella = Dog("Bella", 5)
print(rex.name, rex.age)
print(bella.name, bella.age)You never pass self yourself — Python fills it in. That is why __init__ above has three parameters but Dog("Rex", 3) passes only two arguments.
Methods
A method is a function defined inside a class. Its first parameter is always self, so it can read and change the attributes of the object it was called on. You call it with a dot: acct1.deposit(50). Behind the scenes Python runs BankAccount.deposit(acct1, 50).
Each object has its own attributes
Changing acct1.balance leaves acct2.balance alone, because attributes set on self belong to one object. A variable written directly in the class body, outside any method, is a class attribute instead: it is shared by every object, which is handy for constants such as an interest rate.
Dunder methods: __str__ and __repr__
Methods whose names start and end with two underscores ("dunder" methods) let your objects work with Python's built-in features. By default, printing an object shows something unhelpful like <__main__.Book object at 0x7f...>. Define __str__ to choose what print() and str() show, and __repr__ for a precise, developer-friendly version — Python uses it when the object appears inside a list or in error messages.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title} ({self.pages} pages)"
def __repr__(self):
return f"Book({self.title!r}, {self.pages})"
novel = Book("Dune", 412)
print(novel)
print([novel])Both methods must return a string — not print it.
Quick reference: Python Classes/Objects
- Python OOP Cheat Sheet: Classes, Inheritance, Dunder Methods — In Python OOP you define a `class` as a blueprint, build objects with it, store data in attributes set in `__…
- Python Function vs Method: What Is the Difference? — A **function** is a standalone block of code you call by name, like `len(items)`, while a **method** is a fun…
- Python @staticmethod vs @classmethod: What Is the Difference? — A `@classmethod` receives the **class itself** as its first argument (`cls`) and can create or configure inst…
- Python str() vs repr(): What Is the Difference? — `str()` returns a **readable** version of an object meant for users, while `repr()` returns an **unambiguous*…
- Python isinstance() Function — `isinstance(obj, classinfo)` returns `True` if `obj` is an instance of the class (or of any class in a tuple …
4Python Classes/Objects: syntax
class ClassName:
shared = "value" # class attribute (shared by all objects)
def __init__(self, a, b): # runs when an object is created
self.a = a # instance attribute
self.b = b
def method(self, x): # self = the object it was called on
return self.a + x
def __str__(self): # what print(obj) shows
return f"ClassName({self.a}, {self.b})"
obj = ClassName(1, 2) # create an object (an instance)
obj.a # read an attribute
obj.method(10) # call a method -> 11
5Python Classes/Objects: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def __str__(self):
return f"{self.owner}: ${self.balance}"
acct1 = BankAccount("Asha", 120)
acct2 = BankAccount("Ben")
acct1.deposit(30)
acct2.deposit(15)
print(acct1)
print(acct2)
print("Ben's balance:", acct2.balance)Expected outputAsha: $150
Ben: $15
Ben's balance: 15
7Python Classes/Objects: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1
class BankAccount:starts the blueprint. Defining a class does not create any accounts yet. - Line 2-4
__init__runs every time a new account is created. It stores the owner and the starting balance as attributes onself;balance=0is a default value. - Line 6-7
depositis a method.self.balance += amountchanges the balance of whichever object the method is called on. - Line 9-10
__str__returns the text thatprint()should show for an account. - Line 12-13Calling the class creates two separate objects. Python passes each new object to
__init__asself. Ben's account uses the default balance of 0. - Line 14-15In
acct1.deposit(30),selfisacct1, so only Asha's balance changes (to 150). Ben's account gets 15. - Line 17-18
print()calls each object's__str__method to get the text to display. - Line 19You can read an attribute directly with a dot:
acct2.balanceis the number15.
8Python Classes/Objects: common mistakes
Forgetting self in a method definition
✗ Wrong
class Counter:
def __init__(self):
self.count = 0
def increase():
self.count += 1
clicks = Counter()
clicks.increase()✓ Right
class Counter:
def __init__(self):
self.count = 0
def increase(self):
self.count += 1
clicks = Counter()
clicks.increase()
print(clicks.count)Python always passes the object as the first argument of a method, so every method needs self as its first parameter.
Storing values without self.
✗ Wrong
class Player:
def __init__(self, name):
name = name
score = 0
mia = Player("Mia")
print(mia.name)✓ Right
class Player:
def __init__(self, name):
self.name = name
self.score = 0
mia = Player("Mia")
print(mia.name)name = name only creates a local variable that disappears when __init__ ends. Store values on the object with self.name = ....
Using a class attribute list for per-object data
✗ Wrong
class Team:
members = []
def add(self, name):
self.members.append(name)
red = Team()
blue = Team()
red.add("Asha")
print(blue.members)✓ Right
class Team:
def __init__(self):
self.members = []
def add(self, name):
self.members.append(name)
red = Team()
blue = Team()
red.add("Asha")
print(blue.members)A list in the class body is created once and shared by every object. Create the list in __init__ so each object gets its own.
9Python Classes/Objects: exercises
Write your answer, then press Check. The checks run in your browser.
1. Build a Rectangle class
Write code Easy ✓ CompletedWrite a class Rectangle whose __init__ takes width and height and stores them as attributes with those names. Add a method area() that returns width * height.
class Rectangle:
# write __init__(self, width, height) that stores both values on self
# write area(self) that returns width * height
pass
room = Rectangle(4, 5)
print(room.area())
__init__, write self.width = width (and the same for height). In area, use self.width and self.height.class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
room = Rectangle(4, 5)
print(room.area())
2. Predict the counters
Predict the output Medium ✓ CompletedTwo Counter objects are created and clicked. Type exactly what the program prints.
class Counter:
def __init__(self, start=0):
self.value = start
def click(self):
self.value += 1
return self.value
a = Counter()
b = Counter(10)
a.click()
a.click()
print(b.click())
print(a.value, b.value)
value. b starts at 10, a starts at 0. click() both changes the value and returns it.11
2 11
2 more exercises → 4 more examples
Questions learners ask
What is self in Python?
self is the object a method was called on. When you write acct.deposit(50), Python runs deposit with self set to acct, so self.balance means acct's balance. The name self is a convention, but every Python programmer uses it.
What is the difference between a class and an object?
A class is the definition — the blueprint that lists attributes and methods. An object (instance) is one thing created from that blueprint by calling the class, like BankAccount("Asha"). One class can create any number of independent objects.
Should I define __str__ or __repr__?
Define repr first: it is used in lists, the console and debugging, and print() falls back to it when there is no str. Add str when you also want a friendlier version for end users.
Further reading
10Next lesson
Up nextPython Class Attributes vs Instance AttributesA class attribute is a variable stored once on the class and shared by every object, while an instance attribute is sto…Related:
Python Class Attributes vs Instance AttributesPython Encapsulation: Public, Protected and PrivatePython Dunder (Magic) Methods
← Python pathlib · All Object-Oriented Python lessons · Practise in the IDE