Object-Oriented Programming
Published by Brayan K
Master classes, objects, and design principles to write structured, reusable, professional-grade code.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
You've been using classes all along
Every value in Python has a type, and Variables and Data Types showed type() naming it:
print(type("Ada"))
print(type([1, 2]))
print("ada".upper())
# ✅ Expected output:
# <class 'str'>
# <class 'list'>
# ADAstr and list are classes, and "ada" is an object of the class str. upper() is one of its methods, the functions that String Methods described as belonging to a value. A class statement makes a class of your own: a new type, whose objects carry their own data and have their own methods.
Calling a class makes a new object
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def describe(self):
return f"{self.name} is {self.age}"
rex = Dog("Rex", 3)
fido = Dog("Fido", 7)
print(rex.describe())
print(fido.describe())
print(rex.name, fido.age)
print(type(rex))
# ✅ Expected output:
# Rex is 3
# Fido is 7
# Rex 7
# <class '__main__.Dog'>- class Dog: starts the class, and the functions indented under it are its methods.
- Dog("Rex", 3) makes a new Dog object. Python runs __init__ on it straight away, passing the new object as self and your arguments after it, and self.name = name stores the name on the object, as an attribute.
- rex and fido are two objects of the same class, each with its own attributes, reached with a dot: rex.name, fido.age.
- type(rex) is the class, shown as __main__.Dog: __main__ is the name Python gives the program you run, as in Modules and Packages.
Leave the brackets off, and you don't make a dog: rex = Dog makes rex another name for the class itself.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, "says Woof!")
rex = Dog
rex.bark()
# ✅ Expected error:
# TypeError: Dog.bark() missing 1 required positional argument: 'self'There's no object to be self, so Python says it's missing; the next section shows where self comes from. And assigning an object to another name doesn't copy it, as Lists and Collections showed for lists:
class Dog:
def __init__(self, name):
self.name = name
rex = Dog("Rex")
buddy = rex
buddy.name = "Buddy"
print(rex.name)
print(buddy is rex)
twin = Dog("Buddy")
print(twin is rex)
# ✅ Expected output:
# Buddy
# True
# Falsebuddy = rex gave the same dog a second name, so renaming buddy renamed rex, and is says they're one object. twin is a different dog with the same name.
rex.bark() means Dog.bark(rex)
When you call a method on an object, Python passes the object to the method as its first argument. That's what self is:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, "says Woof!")
rex = Dog("Rex")
fido = Dog("Fido")
rex.bark()
fido.bark()
Dog.bark(rex)
# ✅ Expected output:
# Rex says Woof!
# Fido says Woof!
# Rex says Woof!rex.bark() and Dog.bark(rex) do the same thing: inside bark(), self is rex. That explains the errors about argument counts. Leave self out of a method, and the object has nowhere to go:
class Dog:
def bark():
print("Woof!")
rex = Dog()
rex.bark()
# ✅ Expected error:
# TypeError: Dog.bark() takes 0 positional arguments but 1 was givenThe call rex.bark() has no arguments, yet Python says 1 was given: the object. In the same way, rex.bark("loudly") on the earlier correct Dog with bark(self) stops with TypeError: Dog.bark() takes 1 positional argument but 2 were given.
A method that changes the object and has no return gives None, like a list's sort() in Lists and Collections:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def birthday(self):
self.age += 1
rex = Dog("Rex", 3)
print(rex.birthday())
print(rex.age)
# ✅ Expected output:
# None
# 4Call such a method on a line of its own, then read the attribute.
Only a name after self. is stored on the object
Inside a method, a plain name is a local variable, as in any function. Only a name after self. is stored on the object:
class Dog:
def __init__(self, name):
name = name
rex = Dog("Rex")
print(rex.name)
# ✅ Expected error:
# AttributeError: 'Dog' object has no attribute 'name'name = name set the parameter to itself, and the object never got a name. Reading works the same way: a method that says name where it means self.name stops with NameError: name 'name' is not defined (from Python 3.12, followed by Did you mean: 'self.name'?). Unless the program has a variable called name outside the class, that is. Then there's no error at all:
name = "Max"
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(name, "says Woof!")
Dog("Rex").bark()
# ✅ Expected output:
# Max says Woof!The method found the program's name, not the dog's. Scope: global, nonlocal & LEGB explains where Python looks for a name.
An attribute exists from the moment something assigns it, so one that only a method sets isn't there until that method runs:
class Dog:
def __init__(self, name):
self.name = name
def learn(self, trick):
self.tricks = [trick]
rex = Dog("Rex")
print(rex.tricks)
# ✅ Expected error:
# AttributeError: 'Dog' object has no attribute 'tricks'Make every attribute in __init__, even one that starts empty. With self.tricks = [] there and self.tricks.append(trick) in learn(), a new dog's tricks are [], and after learning two they're ['sit', 'roll over'].
__init__ runs once, when the object is made
class Dog:
def __init__(self, name, age=1):
print("Making", name)
self.name = name
self.age = age
rex = Dog("Rex", 3)
pup = Dog("Pip")
print(rex.age, pup.age)
# ✅ Expected output:
# Making Rex
# Making Pip
# 3 1__init__ takes the arguments you give the class, with defaults if you like, as any function from Functions does. So its argument errors are the familiar ones, naming Dog.__init__():
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog("Rex")
# ✅ Expected error:
# TypeError: Dog.__init__() missing 1 required positional argument: 'age'One argument too many, Dog("Rex", 3, "Labrador"), stops with TypeError: Dog.__init__() takes 3 positional arguments but 4 were given: three, counting self. Misspell __init__, and Python never calls it, so the class takes no arguments at all:
class Dog:
def __int__(self, name, age):
self.name = name
self.age = age
rex = Dog("Rex", 3)
# ✅ Expected error:
# TypeError: Dog() takes no argumentsThe message doesn't mention __int__, so check the spelling: two underscores, init, two underscores. And __init__ mustn't return anything: return "Made " + name in it stops with TypeError: __init__() should return None, not 'str'.
A misspelt attribute is a new attribute
Python checks an attribute's name when you read it, not when you assign it:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
acct = Account("Ada")
acct.balence = 50
print(acct.balance)
print(vars(acct))
print(acct.total)
# ✅ Expected output:
# 0
# {'owner': 'Ada', 'balance': 0, 'balence': 50}
# ✅ Expected error:
# AttributeError: 'Account' object has no attribute 'total'acct.balence = 50 made a new attribute with the misspelt name, and the balance stayed 0. vars() gives the attributes an object holds, as a dictionary, which is how to spot a stray one. Reading a name nobody set is an error, acct.total here. Had the program read acct.balence without setting it, it would have stopped with AttributeError: 'Account' object has no attribute 'balence', which Python on your computer follows with Did you mean: 'balance'? and this site's editor doesn't. __slots__ & Memory Optimization shows a way to make the misspelt assignment an error too.
A class attribute is shared until an object gets its own
A name assigned in the class body, outside any method, is a class attribute: it's stored once, on the class, and every object can read it.
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
rex = Dog("Rex")
fido = Dog("Fido")
print(rex.species, fido.species)
rex.species = "Wolf"
print(rex.species, fido.species, Dog.species)
Dog.species = "Canis lupus familiaris"
print(rex.species, fido.species)
print(vars(rex))
print(vars(fido))
# ✅ Expected output:
# Canis familiaris Canis familiaris
# Wolf Canis familiaris Canis familiaris
# Wolf Canis lupus familiaris
# {'name': 'Rex', 'species': 'Wolf'}
# {'name': 'Fido'}Reading rex.species looks at the object first, then the class. Assigning rex.species gave rex an attribute of its own, so changing Dog.species changed it for fido only, and vars() shows that fido has no species of its own. The sharing is a trap when the class attribute is a list, because appending changes the one list every object reads:
class Dog:
tricks = []
def __init__(self, name):
self.name = name
def learn(self, trick):
self.tricks.append(trick)
rex = Dog("Rex")
fido = Dog("Fido")
rex.learn("sit")
print(fido.tricks)
print(fido.tricks is rex.tricks)
# ✅ Expected output:
# ['sit']
# Trueself.tricks.append() assigned nothing to self.tricks, so it found the class's list and changed it. Make the list in __init__, with self.tricks = [], and each dog gets its own. A default argument such as def __init__(self, name, tricks=[]) sets the same trap; None & NoneType shows the fix. And += through self reads the shared value but writes a new attribute on the object:
class Ticket:
issued = 0
def __init__(self):
self.issued += 1
a = Ticket()
b = Ticket()
print(Ticket.issued, a.issued, b.issued)
# ✅ Expected output:
# 0 1 1Each ticket got an issued of its own, set to 1, and the class's stayed 0. To count objects, change the class's attribute by name, Ticket.issued += 1, and keep each ticket's number with self.number = Ticket.issued. Then print(Ticket.issued, a.number, b.number) shows 2 1 2.
print() and == don't look at your data until you say so
Printing an object of your own class shows something like <__main__.Dog object at 0x…>: the class, and where the object is in memory, which changes from run to run. A __str__ method says what to show instead:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
rex = Dog("Rex", 3)
print(rex)
print(f"Meet {rex}")
print("Meet " + str(rex))
# ✅ Expected output:
# Rex, 3 years old
# Meet Rex, 3 years old
# Meet Rex, 3 years oldprint(), f-strings and str() all use __str__. A list shows its items with __repr__ instead, the method for showing a value to a programmer, and print() falls back to __repr__ when there's no __str__:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Dog({self.name!r}, {self.age})"
dogs = [Dog("Rex", 3), Dog("Fido", 7)]
print(dogs)
print(dogs[0])
print(repr(dogs[0]))
# ✅ Expected output:
# [Dog('Rex', 3), Dog('Fido', 7)]
# Dog('Rex', 3)
# Dog('Rex', 3)!r in an f-string uses repr(), which shows a string with its quotes. A common choice is a __repr__ that looks like the code that makes the object.
Spot the bug: this __str__ shows the right words, and then the program stops.
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
print("Dog called", self.name)
rex = Dog("Rex")
print(rex)
# ✅ Expected output:
# Dog called Rex
# ✅ Expected error:
# TypeError: __str__ returned non-string (type NoneType)__str__ has to return the text, and this one printed it and returned None. Returning a number fails the same way: return self.age stops with TypeError: __str__ returned non-string (type int).
== on your objects asks whether they're the same object, until you say what makes two equal:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
a = Point(1, 2)
b = Point(1, 2)
print(a == b)
print(a == a)
print(b in [a])
# ✅ Expected output:
# False
# True
# FalseTwo points with the same x and y are still two objects, so == says False, and in, which uses ==, can't find a copy. That's also why points.remove(Point(1, 2)) stops with ValueError: list.remove(x): x not in list. An __eq__ method decides:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
a = Point(1, 2)
b = Point(1, 2)
print(a == b)
print(a is b)
print(a != Point(3, 4))
print(b in [a])
# ✅ Expected output:
# True
# False
# True
# True!= uses __eq__ too. One side effect: an object whose class defines __eq__ can't go in a set or be a dictionary key any more, so {Point(1, 2)} stops with TypeError: unhashable type: 'Point', which Python 3.14 words cannot use 'Point' as a set element (unhashable type: 'Point'). Magic Methods & the Python Data Model shows how to allow it, and how to compare a Point with something that isn't one.
When a class is worth writing
A dictionary and a few functions can hold the same data as a class, as in Dictionaries. A class earns its place when its methods keep its data right:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
acct = Account("Ada")
acct.deposit(50)
acct.deposit(25)
print(acct.owner, acct.balance)
acct.deposit(-5)
# ✅ Expected output:
# Ada 75
# ✅ Expected error:
# ValueError: deposit must be more than 0Every deposit goes through deposit(), which refuses a bad amount with raise, from Exception Handling, instead of letting the balance go wrong. A class whose methods never use self holds no data, and plain functions would do its job.
Objects of your own class can't be sorted until you say by what: sorted(dogs) stops with TypeError: '<' not supported between instances of 'Dog' and 'Dog'. A key= function from Lambda Functions picks the attribute:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
dogs = [Dog("Rex", 3), Dog("Fido", 7), Dog("Pip", 1)]
for dog in sorted(dogs, key=lambda d: d.age):
print(dog.name, dog.age)
print(max(dogs, key=lambda d: d.age).name)
# ✅ Expected output:
# Pip 1
# Rex 3
# Fido 7
# FidoSorting with sorted() & key has more ways to do that. For classes that are mostly data, Data Classes & Advanced Class Patterns writes __init__, __repr__ and __eq__ for you, and Inheritance and Polymorphism shows how one class can build on another.
Practice: a book that remembers your page
Finish the Book class. Its three blanks are the method Python runs when a book is made, the parameter that receives the book in read(), and the method print() uses. Each hint under the code fills one blank, in order.
class Book:
def ___(self, title, pages):
self.title = title
self.pages = pages
self.pages_read = 0
def read(___, n):
self.pages_read = min(self.pages_read + n, self.pages)
def ___(self):
return f"{self.title}: {self.pages_read} of {self.pages} pages"
dune = Book("Dune", 412)
emma = Book("Emma", 474)
dune.read(100)
dune.read(50)
emma.read(500)
print(dune)
print(emma)
# 👉 replace ___ with __init__
# 👉 replace ___ with self
# 👉 replace ___ with __str__
# ✅ Expected output:
# Dune: 150 of 412 pages
# Emma: 474 of 474 pagesRun it before filling anything in: three underscores make a valid name, so the class is fine, and Python only complains at Book("Dune", 412), with TypeError: Book() takes no arguments.
On your own: a team's scores
Write a Team class:
- each team has a name and its own list of scores;
- add(score) records a game, and total() adds up the scores;
- printing a team shows, for example, Red: 4 points from 2 games;
- two teams are equal when their names are.
Make Red and Blue, record the scores below, print both teams, and then print whether red == Team("Red") and whether red == blue. If both teams print 7 points from 5 games, the list of scores is a class attribute.
red_scores = [3, 1]
blue_scores = [2, 0, 1]
# your code herered_scores = [3, 1]
blue_scores = [2, 0, 1]
class Team:
def __init__(self, name):
self.name = name
self.scores = []
def add(self, score):
self.scores.append(score)
def total(self):
return sum(self.scores)
def __str__(self):
return f"{self.name}: {self.total()} points from {len(self.scores)} games"
def __eq__(self, other):
return self.name == other.name
red = Team("Red")
blue = Team("Blue")
for score in red_scores:
red.add(score)
for score in blue_scores:
blue.add(score)
print(red)
print(blue)
print(red == Team("Red"), red == blue)
# ✅ Expected output:
# Red: 4 points from 2 games
# Blue: 3 points from 3 games
# True False
Practice quiz
Dog has a method def bark(self): print("Woof!"). A program runs rex = Dog, with no brackets, then rex.bark(). What happens?
- Woof!
- It stops with TypeError: Dog.bark() missing 1 required positional argument: 'self'
- It stops with NameError: name 'rex' is not defined
- Nothing happens
Answer: It stops with TypeError: Dog.bark() missing 1 required positional argument: 'self'. Without brackets, rex is the class itself, not a dog, so there's no object for Python to pass as self.
Dog has a method def bark(): print("Woof!"), with no self. A program runs Dog().bark(). What happens?
- Woof!
- It stops with TypeError: Dog.bark() missing 1 required positional argument: 'self'
- Nothing happens
- It stops with TypeError: Dog.bark() takes 0 positional arguments but 1 was given
Answer: It stops with TypeError: Dog.bark() takes 0 positional arguments but 1 was given. Python passes the object as the first argument, and bark() has no parameter to take it.
Dog's __init__ is def __init__(self, name): name = name. A program runs print(Dog("Rex").name). What happens?
- It stops with AttributeError: 'Dog' object has no attribute 'name'
- Rex
- None
- It stops with NameError: name 'name' is not defined
Answer: It stops with AttributeError: 'Dog' object has no attribute 'name'. name = name only sets the parameter to itself. self.name = name is what stores the name on the object.
A class has def __int__(self, name): self.name = name, a typo for __init__. A program runs Dog("Rex"). What happens?
- Nothing; the dog is made
- It stops with TypeError: Dog.__init__() missing 1 required positional argument: 'name'
- It stops with TypeError: Dog() takes no arguments
- It stops with AttributeError: 'Dog' object has no attribute 'name'
Answer: It stops with TypeError: Dog() takes no arguments. With no __init__, Python uses one that takes no arguments, and the message never mentions __int__.
rex = Dog("Rex"), where __init__ sets self.name. Then rex.nmae = "Max", then print(rex.name). What prints?
- Rex
- Max
- It stops with AttributeError: 'Dog' object has no attribute 'nmae'
- It stops with NameError
Answer: Rex. Assigning to a misspelt attribute makes a new attribute, nmae, without an error. name is untouched.
class Ticket: issued = 0, and __init__ runs self.issued += 1. After a = Ticket() and b = Ticket(), what does print(Ticket.issued, a.issued, b.issued) show?
- 2 2 2
- 2 1 2
- 0 1 1
- It stops with AttributeError
Answer: 0 1 1. self.issued += 1 reads the class's 0 and writes 1 to a new attribute on each ticket. The class's own issued stays 0.
class Dog has tricks = [] in the class body, and learn() runs self.tricks.append(trick). After rex.learn("sit"), what does print(fido.tricks) show?
- []
- ['sit']
- None
- It stops with AttributeError: 'Dog' object has no attribute 'tricks'
Answer: ['sit']. There's one list, on the class, and every dog reads it. Make the list in __init__ to give each dog its own.
class Point stores x and y and has no __eq__. What does print(Point(1, 2) == Point(1, 2)) show?
- True
- (1, 2)
- It stops with a TypeError
- False
Answer: False. Without __eq__, == asks whether the two are the same object, and they're two objects.
Continue this course
- Previous: Modules and Packages
- Next: Inheritance and Polymorphism — Build class hierarchies and reuse code through inheritance
- Quick reference: Python cheat sheet › Classes
- From the blog: Object-Oriented Programming in Python
Frequently asked questions
Is self a keyword? Could I call it something else?
It's an ordinary parameter name, not a keyword: def bark(me): works, with me.name inside. Every Python programmer expects self, though, so use it.
Is __init__ the constructor?
That's what it's often called. Strictly, Python makes the object first, with a method called __new__, and then calls __init__ to set it up, which is why __init__ is handed self. Magic Methods & the Python Data Model covers __new__.
How do I make an attribute private?
Python has no private attributes. A name that starts with one underscore, like _balance, is a convention meaning 'not for use outside the class', but it can still be read and changed. Two underscores make Python rename it: self.__pin is stored as _Account__pin, which keeps classes from clashing rather than hiding anything. Properties & Descriptors shows @property, which lets a class control how an attribute is read and set.
What are @classmethod and @staticmethod?
Methods that don't take the object. A @classmethod gets the class as its first parameter, usually named cls, and is often used as another way to make objects, such as Temperature.from_fahrenheit(212). A @staticmethod gets neither the object nor the class: it's a plain function kept in the class because it belongs with it. Lines that start with @ are decorators, which Decorators & Advanced Features explains.
Why do some classes say class Dog(object):?
In Python 3 it means the same as class Dog:, because every class is built on object either way. Brackets after a class's name name a class to build on, which Inheritance and Polymorphism explains.