01Programming
Advanced Python & OOP
As projects grow, scripts turn into systems. Object-oriented programming organizes code into reusable, self-contained pieces you can trust.
Classes and objects
A class is a blueprint; an object is a thing built from it. The class bundles data (attributes) with the functions that act on that data (methods). Instead of loose variables and functions, related state and behavior live together.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner # attribute
self.balance = balance
def deposit(self, amount): # method
self.balance += amount
return self.balance
acc = Account("Sara", 100)
acc.deposit(50) # 150 The four pillars
- Encapsulation — bundle data with its methods and hide internals.
- Inheritance — a class can extend another, reusing and specializing it.
- Polymorphism — different classes respond to the same method name in their own way.
- Abstraction — expose a simple interface, hide the complex implementation.
Why it matters for data science
scikit-learn, PyTorch and Pandas are all built with OOP — every model is an object with .fit() and .predict(). Understanding classes lets you build custom transformers, extend library classes, and structure a project so it stays maintainable as it scales.
Test yourself What does the `self` parameter refer to in a method?
The specific object the method is called on. self.balance means 'this object's balance', so each Account keeps its own state separate from others.
Key takeaways
- A class bundles data + methods; objects are instances that keep their own state.
- Encapsulation, inheritance, polymorphism and abstraction are the four pillars.
- Every ML library is OOP — mastering classes lets you extend and structure real projects.