A beginner's guide to Python object-oriented programming (OOP)
In Python, everything is an object, so you've been using OOP since your first line of code, even if you didn't know it.
Programming is an art, and as in art, choosing the right tools and techniques is essential to produce your best work. Object-oriented programming (OOP) is one of the most important techniques you can learn as a Python developer.
As your programs grow, organizing code into objects keeps it readable, reusable, and easier to change. In this guide, you'll learn what OOP is, why it's useful, and how to use classes, objects, and the four pillars of OOP in Python, with examples you can run. All the code was tested with Python 3.13 and 3.15.
An example Python program#
Before digging in, have you ever written a Python program like this one?
secret_number = 20
while True:
number = input("Guess the number: ")
try:
number = int(number)
except ValueError:
print("Sorry, that is not a number")
continue
if number > secret_number:
print(number, "is greater than the secret number")
elif number < secret_number:
print(number, "is less than the secret number")
else:
print("You guessed the number:", secret_number)
breakThis simple number guesser works perfectly. But what if you had to add a new feature, for example, "If the guess is a multiple of the secret number, give the user a hint"?
With every new feature, the program grows more conditionals, and soon it's hard to read and change. That's one of the problems object-oriented programming helps you solve.
Requirements to learn Python OOP#
Before you start with object-oriented programming, you should be comfortable with the Python basics:
- Variables: Names that point to values (objects, as you'll see in this article).
- Operators: Arithmetic operators, such as
+,-,*,/,//, and%, and comparison and boolean operators. - Built-in data types: Numbers (
int,float), strings, lists, tuples, dictionaries, sets, and booleans. - Conditionals:
if,elif, andelsestatements. - Loops:
forandwhileloops. - Functions: Reusable blocks of code that you define with
def, and the arguments you pass to them. - Running Python: Running a script with
python3 script.py, and opening the interactive shell withpython3. See our guide to Python commands if you need a refresher.
If you're comfortable with these concepts, you're ready for object-oriented programming.
What is object-oriented programming in Python?#
Object-oriented programming is a programming paradigm, a way of structuring programs, in which you model the problem you're solving as a set of objects.
An object combines data, called attributes, with behavior, called methods. You can think of objects as the real things around you. For example, consider a calculator:

Notice that the attributes are nouns, while the methods are verbs. This is the central idea of object-oriented programming: you build objects that hold specific data and the functionality that works with it.
Why use object-oriented programming in Python?#
OOP helps you write programs that are easier to understand, extend, and maintain. Many popular Python frameworks and libraries are built with classes, such as Django, pandas, and PyTorch, and you use OOP every time you work with them.
Advantages of Python OOP#
Here are the main reasons to learn object-oriented programming in Python.
You can use it in many languages
OOP is a paradigm, not a Python feature. Many popular languages are object-oriented or support objects, including:
- Java
- PHP
- Ruby
- JavaScript and TypeScript
- C#
- Kotlin
Once you learn OOP in Python, you'll recognize the same ideas in these languages, which makes them easier to learn.
It helps you develop faster
Developing faster doesn't mean writing fewer lines of code. It means adding features in less time without breaking what already works.
Object-oriented programming lets you reuse code through classes and inheritance, and hide details behind simple interfaces through abstraction. The result is code that's shorter, clearer, and easier to read.
Developers spend much more time reading code than writing it. That's why readable code matters more than shipping a feature as fast as possible.

It helps you avoid spaghetti code
Remember the number guesser at the start of this article? If you keep adding features to it, you'll end up with many nested if statements. Code like this, a tangle that's hard to follow, is called spaghetti code.
OOP lets you split the logic into small objects, each responsible for one thing, instead of one long block of nested conditions.
It improves how you think about problems
With some experience in OOP, you'll start to see problems as small, specific objects that work together. This makes it easier to plan a project and divide the work.
Procedural programming vs object-oriented programming#
Most beginners start with procedural, or structured, programming, because it's the simplest way to write a small program. You give the computer a list of instructions, and it runs them from top to bottom.
Here's a procedural program for a coffee shop. It asks for your budget and sells you the biggest coffee you can afford:
small = 2
regular = 5
big = 6
try:
budget = float(input("What is your budget? "))
except ValueError:
raise SystemExit("Please enter a number")
if budget >= big:
print("Here's your big coffee.")
if budget == big:
print("It's complete!")
else:
print(f"Your change is ${budget - big:.2f}")
elif budget >= regular:
print("Here's your regular coffee.")
if budget == regular:
print("It's complete!")
else:
print(f"Your change is ${budget - regular:.2f}")
elif budget >= small:
print("Here's your small coffee.")
if budget == small:
print("It's complete!")
else:
print(f"Your change is ${budget - small:.2f}")
else:
print("Sorry, you can't afford any coffee")This code works, but it has three problems:
- The same logic is repeated for every coffee.
- It uses many nested
ifstatements. - Adding a new size, or changing how sales work, means editing many places.
Here's the same program written with OOP. Don't worry if you don't understand it all yet, as we'll cover each concept in this article:
class Coffee:
def __init__(self, name, price):
self.name = name
self.price = price
def can_afford(self, budget):
return budget >= self.price
def sell(self, budget):
change = budget - self.price
if change == 0:
return f"Here's your {self.name} coffee. It's complete!"
return f"Here's your {self.name} coffee. Your change is ${change:.2f}"
menu = [Coffee("big", 6), Coffee("regular", 5), Coffee("small", 2)]
try:
budget = float(input("What is your budget? "))
except ValueError:
raise SystemExit("Please enter a number")
for coffee in menu:
if coffee.can_afford(budget):
print(coffee.sell(budget))
break
else:
print("Sorry, you can't afford any coffee")The Coffee class is a template for coffees. Each coffee has two attributes, name and price, and two methods: can_afford() checks a budget, and sell() handles the sale. The menu list holds three coffee objects, and the loop sells the first one the user can afford. The else block of the for loop runs only if the loop finishes without break, meaning no coffee was affordable.
Both programs give the same results. For example, with a budget of 5.5, both print Here's your regular coffee. Your change is $0.50. But adding a new size to the OOP version takes a single line in menu, and the selling logic lives in one place.
Here's how the two approaches compare:
| Object-oriented programming | Procedural programming |
|---|---|
| Easier to maintain as the program grows | Harder to maintain as the program grows |
| Avoids repetition (Don't Repeat Yourself) | Logic is often repeated |
| Small pieces of code reused in many places | Long blocks of code in few places |
| Organized around objects | Organized around steps |
| Steeper learning curve | Simpler to learn |
| Suits large projects | Suits small scripts |
Neither paradigm is always better. OOP can be overkill for a small script, and Python lets you mix both, so use classes where they make your code clearer.
Everything is an object in Python#
Here's a secret: you've been using objects all along. In Python, everything is an object, so you've been using OOP since your first line of code, even if you didn't know it.
Remember the definition: an object combines data (attributes) with behavior (methods). That matches every value in Python. A string holds data, its characters, and has behaviors, such as upper() and lower(). The same applies to integers, floats, lists, dictionaries, and even functions.
Attributes and methods#
Attributes are variables that belong to an object, while methods are functions that belong to an object.
Open the Python shell by typing python3 (or python on Windows) in your terminal, and try this:
>>> site = "Sevalla, Application Hosting, Database Hosting, and Static Site Hosting"
>>> site.upper()
'SEVALLA, APPLICATION HOSTING, DATABASE HOSTING, AND STATIC SITE HOSTING'The second line calls a string method, upper(), which returns the string in uppercase. It doesn't change the original string, because strings in Python are immutable:
>>> site
'Sevalla, Application Hosting, Database Hosting, and Static Site Hosting'The type() function returns the type of an object, which is the class the object belongs to:
>>> type(site)
<class 'str'>The dir() function lists all the attributes and methods of an object:
>>> dir(site)
['__add__', '__class__', ..., 'upper', 'zfill']Names that start and end with double underscores, such as __class__, are special attributes and methods that Python uses internally. For example, __class__ holds the object's class, which is what type() returns:
>>> site.__class__
<class 'str'>You can explore the attributes and methods of any data type this way. To learn more about the built-in types, see the official documentation.
Your first object in Python#
A class is a template that lets you create your own objects, with the attributes and methods you define. You can think of a class as a cookie cutter, and the objects you create with it as the cookies. Each cookie has the same shape, but you can decorate each one differently.
Each object you create from a class is called an instance of that class.

To define a class in Python, use the class keyword, followed by its name. Let's create a class named Cookie:
class Cookie:
passClass names use CapWords, also called PascalCase, where each word starts with a capital letter, such as Cookie or ShoppingCart. This is the convention in PEP 8, Python's style guide.
Paste the class into your Python shell. To create an instance, call the class like a function:
>>> cookie1 = Cookie()You've just created your first object in Python! You can check its identity and type:
>>> id(cookie1)
140130610977040
>>> type(cookie1)
<class '__main__.Cookie'>The id() function returns a number that's unique to each object while it exists, so you'll see a different value. Its type is Cookie.
You can also check whether an object is an instance of a class with the isinstance() function:
>>> isinstance(cookie1, Cookie)
True
>>> isinstance(cookie1, int)
False
>>> isinstance("a string", Cookie)
FalseThe constructor method#
The __init__() method sets up a new object's initial state. Python calls it automatically every time you create an instance, so it's often called the constructor. Let's change the Cookie class so that it accepts some parameters:
class Cookie:
def __init__(self, name, shape, chips="Chocolate"):
# Instance attributes
self.name = name
self.shape = shape
self.chips = chipsEvery cookie now needs a name and a shape. The chips parameter has a default value, "Chocolate", so it's optional.
The first parameter, self, refers to the instance being created. Python passes it automatically, so you don't include it when you create a cookie.
Paste the new class into the shell and try to create a cookie without arguments:
>>> cookie2 = Cookie()
TypeError: Cookie.__init__() missing 2 required positional arguments: 'name' and 'shape'You get an error, because a cookie needs a name and a shape. Pass them, and it works:
>>> cookie2 = Cookie("Awesome cookie", "Star")To access the attributes of an instance, use dot notation:
>>> cookie2.name
'Awesome cookie'
>>> cookie2.shape
'Star'
>>> cookie2.chips
'Chocolate'Methods#
Methods are functions defined inside a class. Let's add a bake() method to the Cookie class:
class Cookie:
def __init__(self, name, shape, chips="Chocolate"):
self.name = name
self.shape = shape
self.chips = chips
def bake(self):
print(f"This {self.name} is being baked with the shape {self.shape} and {self.chips} chips")
print("Enjoy your cookie!")Like __init__(), every method receives the instance as self, so it can use the object's attributes. To call a method, use dot notation:
>>> cookie3 = Cookie("Baked cookie", "Tree")
>>> cookie3.bake()
This Baked cookie is being baked with the shape Tree and Chocolate chips
Enjoy your cookie!For classes that mostly hold data, Python's dataclasses module can write the __init__() method for you. You declare the attributes with type hints:
from dataclasses import dataclass
@dataclass
class Cookie:
name: str
shape: str
chips: str = "Chocolate"This class works like the one above, and it also gets a readable representation for free: printing Cookie("Awesome cookie", "Star") shows Cookie(name='Awesome cookie', shape='Star', chips='Chocolate').
The 4 pillars of OOP in Python#
Object-oriented programming rests on four main principles.
1. Abstraction#
Abstraction hides the internal details of how something works, and exposes only what you need to use it.
You use abstraction every day. You know how to use your phone without knowing what happens inside it when you open an app. Python itself is another example: you can write great software without knowing how the interpreter works.
In code, abstraction means identifying what objects in a problem have in common, and defining that in a class with a simple interface. Code that uses the class calls its methods without worrying about how they're implemented.
2. Inheritance#
Inheritance lets you define a new class, called a subclass or child class, based on an existing class, called a superclass, base class, or parent class. The subclass gets all the attributes and methods of the superclass, and can add its own or change them.
Its main purpose is to follow the DRY principle (Don't Repeat Yourself): you write shared code once, in the superclass, and reuse it in every subclass.
You can think of it like biological inheritance. Children inherit traits from their parents, but they also have their own. Python even supports multiple inheritance, where a class inherits from more than one parent class.
3. Polymorphism#
Polymorphism means "many forms." In OOP, it means that different classes can provide the same method, each in its own way, so you can use their objects interchangeably.
For example, if every shape class has a get_area() method, you can call shape.get_area() on any shape, without knowing whether it's a square or a circle. Each class calculates the area with its own formula. A subclass that redefines a method from its superclass is overriding that method.
4. Encapsulation#
Encapsulation bundles data with the methods that work on it, and protects the data from being changed in invalid ways.
Python doesn't have private attributes like Java or C#. Instead, it relies on conventions:
- A name that starts with one underscore, such as
_height, is internal. Code outside the class shouldn't use it directly, although Python doesn't stop it. - A name that starts with two underscores, such as
__balance, triggers name mangling: Python renames it to_ClassName__balance, so it's harder to access or override by accident.
To control how an attribute is read and changed, Python uses properties instead of explicit getter and setter methods. For example, a Human class can make sure nobody sets an impossible height:
class Human:
def __init__(self, name, height):
self.name = name
self.height = height # Uses the setter below
@property
def height(self):
return self._height
@height.setter
def height(self, value):
if not 0 < value < 3:
raise ValueError("Height must be between 0 and 3 meters")
self._height = valueThe @property decorator turns height into a property: reading person.height calls the first method, and assigning to it calls the setter, which validates the value:
>>> person = Human("Ada", 1.7)
>>> person.height
1.7
>>> person.height = 5
ValueError: Height must be between 0 and 3 metersThe value itself is stored in _height, and code that uses the class works with height as if it were a regular attribute.
Build an area calculator#
Now that you've learned the main concepts of OOP, let's apply them to a small project: a calculator that finds the area of these shapes:
- Rectangle
- Square
- Triangle
- Circle
- Regular hexagon
Create a file named calculator.py. We'll add each class to it step by step, and you'll find the complete file at the end of this section.
Shape base class#
All of these shapes are 2D shapes with an area. That's the common behavior to abstract into a base class, Shape, with a get_area() method that each shape must implement:
from abc import ABC, abstractmethod
from math import pi, sqrt
class Shape(ABC):
@abstractmethod
def get_area(self):
"""Return the area of the shape."""
def __str__(self):
return f"The area of this {self.__class__.__name__} is: {self.get_area():.2f}"Let's break this down:
Shapeinherits fromABC, which makes it an abstract base class. You can't create aShapedirectly, only its subclasses.- The
@abstractmethoddecorator marksget_area()as a method every subclass must define. If a subclass forgets, Python raises an error when you create an instance of it. __str__()is a special method, like__init__(). It defines how an object looks when you print it. Every shape inherits it.self.__class__.__name__is the name of the object's class, such as"Triangle".
If you try to create a Shape, Python stops you:
>>> Shape()
TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'get_area'Rectangle class#
A rectangle's area is its width multiplied by its height. To inherit from a class, put the superclass in parentheses after the class name:
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def get_area(self):
return self.width * self.heightSquare class#
A square is a rectangle whose sides are all equal, so it can reuse the rectangle's formula. The Square class only changes the constructor, so that it takes a single side:
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)The super() function calls a method of the superclass. Here, it calls the Rectangle constructor, passing side as both the width and the height. Square inherits get_area() and __str__() without changes.
Triangle class#
A triangle's area is half the area of the rectangle around it: half the base multiplied by the height. So Triangle inherits from Rectangle and overrides get_area():
class Triangle(Rectangle):
def __init__(self, base, height):
super().__init__(base, height)
def get_area(self):
return super().get_area() / 2This is polymorphism in action. Triangle has a get_area() method like every other shape, but its own version calls the rectangle's version with super().get_area(), then divides the result by two.
Circle class#
A circle's area is π multiplied by its radius squared (πr²). A circle doesn't have a width and height, so Circle inherits directly from Shape, with its own constructor and get_area():
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def get_area(self):
return pi * self.radius**2The pi constant comes from Python's math module, which you imported at the top of the file.
Regular hexagon class#
The area of a regular hexagon depends only on the length of its side: three times the square root of three, multiplied by the side squared, divided by two ((3√3 × s²) / 2). It uses the sqrt() function from the math module:
class Hexagon(Shape):
def __init__(self, side):
self.side = side
def get_area(self):
return 3 * sqrt(3) * self.side**2 / 2Testing the classes#
Here's the complete calculator.py file:
from abc import ABC, abstractmethod
from math import pi, sqrt
class Shape(ABC):
@abstractmethod
def get_area(self):
"""Return the area of the shape."""
def __str__(self):
return f"The area of this {self.__class__.__name__} is: {self.get_area():.2f}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def get_area(self):
return self.width * self.height
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
class Triangle(Rectangle):
def __init__(self, base, height):
super().__init__(base, height)
def get_area(self):
return super().get_area() / 2
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def get_area(self):
return pi * self.radius**2
class Hexagon(Shape):
def __init__(self, side):
self.side = side
def get_area(self):
return 3 * sqrt(3) * self.side**2 / 2To try the classes, run the file with the -i flag. Python runs the file, then opens the interactive shell with your classes loaded:
python3 -i calculator.pyNow create some shapes and print them:
>>> print(Rectangle(1, 2))
The area of this Rectangle is: 2.00
>>> print(Square(4))
The area of this Square is: 16.00
>>> print(Triangle(2, 3))
The area of this Triangle is: 3.00
>>> print(Circle(4))
The area of this Circle is: 50.27
>>> print(Hexagon(3))
The area of this Hexagon is: 23.38Thanks to polymorphism, you can also handle different shapes in the same way, for example, in a loop:
>>> for shape in [Square(2), Circle(1), Triangle(4, 5)]:
... print(shape)
...
The area of this Square is: 4.00
The area of this Circle is: 3.14
The area of this Triangle is: 10.00Challenge#
Add a run() function or a Calculator class that asks the user to choose a shape, enter its measurements, and see its area. Then add a new shape, such as a trapezoid, and notice how little code you need to change.
Summary#
Object-oriented programming is a paradigm in which you solve problems by modeling them as objects that combine data and behavior. Once you understand OOP in Python, you can apply the same ideas in languages like Java, PHP, JavaScript, and C#.
In this article, you learned:
- What object-oriented programming is, and why it's useful.
- How OOP compares to procedural programming.
- That everything in Python is an object.
- How to define classes and create instances, with constructors, attributes, and methods.
- The four pillars of OOP: abstraction, inheritance, polymorphism, and encapsulation.
- How to apply them in a project with abstract base classes,
super(), and method overriding.
To keep learning, check out our guide to Python tutorials. And when your Python app is ready to go live, you can deploy it from Git with Sevalla's Application Hosting.