Python OOP
Python · Functions & OOP
Theory
Object-Oriented Programming (OOP) is a way of organising code around objects - things that bundle data (attributes) with the behaviour that works on that data (methods). You describe a kind of thing once as a class, then create as many objects of it as you need. An Employee class might hold name and salary and offer a give_raise() method; every employee object carries its own values but shares the same methods.
OOP rests on four ideas: encapsulation (keep data and methods together and guard internal state), abstraction (expose a simple interface, hide the details), inheritance (a child class reuses a parent's code) and polymorphism (different classes respond to the same method call in their own way). Libraries you use daily are built this way: a pandas DataFrame is an object with data inside and methods like groupby().
Why we use it
As programs grow, loose variables and functions become hard to track. OOP groups related data and logic into self-contained units, so code mirrors real-world things, is easier to extend and is safer to change.
When to use it
Use classes when you model things that have both state and behaviour (accounts, employees, ML models) or need many similar objects. For a short script that just transforms data step by step, plain functions are often simpler.
How it works
- Identify a real-world thing (e.g. Employee)
- List its data: name, salary
- List its actions: give_raise(), describe()
- Write a class that holds both
- Create objects from the class
- Need a specialised kind (Manager)? Yes: Inherit and extend the class. No: Use the class as it is.
- Objects call methods on their own data
Syntax
class ClassName:
def __init__(self, ...):
...Example
class Employee:
def __init__(self, name):
self.name = nameKey points
- Encapsulates related data and functions together
- Supports inheritance and polymorphism
- A class is the blueprint; objects are the things built from it
- Methods always receive the object itself as the first parameter, self
- Everything in Python (ints, lists, DataFrames) is already an object