Here’s a quick “crash‑course” on doing Object‑Oriented Programming in Python 🐍
1. Core OOP Concepts
- Class
A blueprint for objects.
- Object (Instance)
A concrete “thing” created from a class.
- Encapsulation
Hiding internal state (using _ or __ prefixes).
- Inheritance
Derive a new class from an existing one.
- Polymorphism
Same interface, different underlying behavior.
- Abstraction
Expose only what’s necessary (via abstract base classes or interfaces).
2. Defining & Instantiating a Class
class Dog:
"""Simple Dog class demonstrating encapsulation."""
def __init__(self, name: str, age: int):
self.name = name # public attribute
self.__age = age # private attribute (name‑mangled)
def speak(self) -> str:
return f"{self.name} says woof!"
# getter for private attribute
@property
def age(self) -> int:
return self.__age
# setter for private attribute
@age.setter
def age(self, value: int):
if value < 0:
raise ValueError("Age cannot be negative")
self.__age = value
# Instantiate
my_dog = Dog("Rex", 3)
print(my_dog.speak()) # Rex says woof!
print(my_dog.age) # 3
my_dog.age = 4 # OK
3. Inheritance & Method Overriding
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this!")
class Cat(Animal):
def speak(self):
return f"{self.name} says meow!"
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
animals = [Cat("Luna"), Dog("Buddy")]
for a in animals:
print(a.speak())
What’s happening?
Cat and Dog inherit from Animal.
- They override
speak().
- We can treat them all as
Animal—that’s polymorphism.
4. Encapsulation & Name Mangling
- Prefix with
_ → “protected” by convention.
- Prefix with
__ → name‑mangled to discourage external access.
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acct = BankAccount()
acct.deposit(100)
print(acct.get_balance()) # 100
# print(acct.__balance) # Error! AttributeError
5. Abstract Base Classes (Abstraction)
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.1416 * self.r**2
# shape = Shape() # Error: can’t instantiate abstract class
c = Circle(5)
print(c.area()) # 78.54
6. Putting It All Together
class Employee:
def __init__(self, name, salary):
self.name = name
self._salary = salary # “protected”
def work(self):
print(f"{self.name} is working...")
class Manager(Employee):
def work(self):
super().work()
print(f"{self.name} is also managing the team!")
e = Employee("Alice", 50000)
m = Manager("Bob", 80000)
for person in (e, m):
person.work()
Tips & Best Practices
- Use
@property for controlled access.
- Favor composition over deep inheritance hierarchies.
- Keep methods small & focused.
- Follow PEP8 naming conventions.
Any particular area you’d like to dive deeper into? 🚀