Object-Oriented Programming in Python
Classes & Objects
Define custom types grouping data and behavior:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}, {self.age} years old."
# Instantiate and use
p = Person("Alice", 30)
print(p.greet()) # Hi, I'm Alice, 30 years old.
Inheritance
Create subclasses inheriting attributes and methods, overriding when needed:
class Employee(Person):
def __init__(self, name, age, role):
super().__init__(name, age)
self.role = role
def greet(self):
base = super().greet()
return f"{base} I work as a {self.role}."
e = Employee("Bob", 28, "Developer")
print(e.greet()) # Hi, I'm Bob, 28 years old. I work as a Developer.
Encapsulation
Use private attributes (_ or __) and @property:
class Account:
def __init__(self, balance=0):
self.__balance = balance
@property
def balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
acct = Account(100)
print(acct.balance) # 100
# acct.__balance # AttributeError
Polymorphism
Different classes can implement the same method name:
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
for animal in (Dog(), Cat()):
print(animal.speak()) # Woof! Meow!
Special Methods
Customize behavior with methods like __str__, __repr__, __eq__:
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1, v2 = Vector(1, 2), Vector(3, 4)
print(v1 + v2) # Vector(4, 6)