In the beginner stage, you learned how to create classes and objects. Now it's time to go deeper and explore advanced Object-Oriented Programming concepts used in real-world applications.
This lesson will help you understand how to design scalable, reusable, and maintainable systems using OOP.
You will learn:
✔ Class vs instance attributes
✔ Class methods & static methods
✔ Inheritance (single & multiple)
✔ Method overriding
✔ Encapsulation (private attributes)
✔ Magic (dunder) methods
Defined inside __init__ and belong to each object:
class Car:
def __init__(self, brand):
self.brand = brandShared by all objects:
class Car:
wheels = 4 # class attribute
def __init__(self, brand):
self.brand = brandc1 = Car("Toyota")
c2 = Car("BMW")
print(c1.wheels) # 4
print(c2.wheels) # 4@classmethod)Works with the class, not the instance:
class Student:
school = "MofidTech"
@classmethod
def change_school(cls, name):
cls.school = name@staticmethod)Independent utility function:
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(2, 3))Inheritance allows one class to reuse another.
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def bark(self):
print("Woof")class A:
def method_a(self):
print("A")
class B:
def method_b(self):
print("B")
class C(A, B):
passChild class modifies parent behavior:
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def speak(self):
print("Woof")Use _ or __ to protect attributes:
class Bank:
def __init__(self, balance):
self.__balance = balance # private
def get_balance(self):
return self.__balanceb = Bank(1000)
print(b.get_balance())Special methods that define behavior:
__str__class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person: {self.name}"
p = Person("Ali")
print(p)__len__class MyList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.valueCreate a class Book with:
Create a class method that updates a class variable.
Create a class Vehicle and a subclass Car.
Create a class with a private variable and getter.
Create a class with __str__.
In this lesson, you explored advanced OOP concepts that are essential for real-world development:
These concepts are heavily used in frameworks like Django, Flask, and FastAPI.