LEARN COMPLETE PYTHON IN 24 HOURS

🟦 Table of Contents – Python OOP

🔹 1. Introduction to Object-Oriented Programming (OOP)

  • 1.1 What is OOP and Why Learn It?

  • 1.2 Real-World Examples – Class vs Object

  • 1.3 The 4 Pillars of OOP in Python

  • 1.4 Procedural vs Object-Oriented Programming

🔹 2. Classes and Objects – Basic Building Blocks

  • 2.1 Creating Classes

  • 2.2 Creating Objects

  • 2.3 The init Method and self Parameter

  • 2.4 Instance Variables vs Class Variables

  • 2.5 str and repr

🔹 3. Encapsulation – Data Hiding and Protection

  • 3.1 Public, Protected and Private Members

  • 3.2 Name Mangling

  • 3.3 @property, @setter, @deleter

🔹 4. Inheritance – Reusing Code

  • 4.1 Single Inheritance

  • 4.2 Using super()

  • 4.3 Method Overriding and Polymorphism

  • 4.4 Multiple Inheritance and MRO

🔹 5. Polymorphism – One Name, Different Behavior

  • 5.1 Method Overriding

  • 5.2 Operator Overloading

  • 5.3 Duck Typing

  • 5.4 Abstract Base Classes

🔹 6. Class Methods, Static Methods and Decorators

  • 6.1 @classmethod

  • 6.2 @staticmethod

  • 6.3 Alternative Constructors

  • 6.4 @property

🔹 7. Advanced OOP Concepts

  • 7.1 Composition vs Inheritance

  • 7.2 Data Classes (@dataclass)

  • 7.3 Magic Methods / Dunder Methods

  • 7.4 Metaclasses

🔹 8. Real-World OOP Projects & Best Practices

  • 8.1 Bank Account System

  • 8.2 Library Management System

  • 8.3 Employee Payroll System

  • 8.4 OOP Best Practices

🔹 9. Common Mistakes & Interview Preparation

  • 9.1 Common OOP Mistakes

  • 9.2 Python OOP Interview Questions

  • 9.3 Debugging OOP Code

🔹 10. Next Steps After Mastering OOP

  • 10.1 Design Patterns

  • 10.2 Decorators and Context Managers

  • 10.3 OOP in FastAPI / Django

  • 10.4 Resources

2. Object-Oriented Programming (OOP) in Depth

OOP lets you model real-world entities as objects with data (attributes) and behavior (methods). Python’s OOP is flexible, powerful, and very “Pythonic”.

2.1 Classes & Objects – Advanced Features

Class → Blueprint Object → Instance of the class

Basic syntax (recap + advanced)

Python

class Person: # Class attribute (shared by all instances) species = "Homo sapiens" def init(self, name, age): # Instance attributes self.name = name self.age = age def introduce(self): return f"Hi, I'm {self.name}, {self.age} years old." # Creating objects (instances) p1 = Person("Anshuman", 25) p2 = Person("Rahul", 24) print(p1.introduce()) # Hi, I'm Anshuman, 25 years old. print(p1.species) # Homo sapiens print(p2.species) # Homo sapiens (shared)

Advanced features already in use:

  • self → reference to the current instance

  • Class attributes vs instance attributes

  • Methods are functions attached to the class

2.2 init, self, str, repr

Special (magic/dunder) methods:

  • init → constructor (called when object is created)

  • self → explicit reference to instance (Python passes it automatically)

str → human-readable string (used by print()) repr → unambiguous, developer-friendly string (used in REPL/debugger)

Python

class Book: def init(self, title, author, year): self.title = title self.author = author self.year = year def str(self): return f"{self.title} by {self.author} ({self.year})" def repr(self): return f"Book(title='{self.title}', author='{self.author}', year={self.year})" b = Book("Python Mastery", "Anshuman", 2026) print(b) # Python Mastery by Anshuman (2026) ← str print(repr(b)) # Book(title='Python Mastery', author='Anshuman', year=2026)

Tip: Always implement both — str for users, repr for debugging.

2.3 Inheritance & super()

Inheritance lets a child class reuse code from a parent class.

Python

class Employee: def init(self, name, salary): self.name = name self.salary = salary def work(self): return f"{self.name} is working." class Developer(Employee): def init(self, name, salary, language): # super() calls parent's init super().__init__(name, salary) self.language = language def work(self): return f"{self.name} is coding in {self.language}." dev = Developer("Anshuman", 120000, "Python") print(dev.work()) # Anshuman is coding in Python. print(dev.salary) # 120000 (inherited)

super() is better than hardcoding parent class name — supports multiple inheritance.

2.4 Method Overriding & Polymorphism

Overriding → Child redefines parent method Polymorphism → Same method name, different behavior

Python

class Animal: def speak(self): return "Some sound..." class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" animals = [Dog(), Cat(), Animal()] for animal in animals: print(animal.speak()) # Woof! / Meow! / Some sound...

Duck typing in Python: "If it walks like a duck and quacks like a duck, it’s a duck."

2.5 Encapsulation: Private & Protected Members

Python uses naming conventions (no strict private):

  • singleunderscore → protected (by convention, don’t access directly)

  • __double_underscore → name mangling (pseudo-private)

Python

class BankAccount: def init(self, owner, balance=0): self.owner = owner self._balance = balance # protected self.__secret_pin = 1234 # name mangled def deposit(self, amount): if amount > 0: self._balance += amount def get_balance(self): return self._balance acc = BankAccount("Anshuman", 10000) print(acc._balance) # 10000 (works but discouraged) # print(acc.__secret_pin) # AttributeError print(acc._BankAccount__secret_pin) # 1234 (name mangled)

Best practice: Use _ for "don't touch this" and properties for controlled access.

2.6 Properties (@property, @setter, @deleter)

Make attributes look like variables but control access.

Python

class Circle: def init(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): if value < 0: raise ValueError("Radius cannot be negative") self._radius = value @property def area(self): return 3.14159 self._radius * 2 @area.deleter def area(self): print("Area cache cleared (if any)") c = Circle(5) print(c.radius) # 5 ← looks like attribute print(c.area) # 78.53975 ← computed property c.radius = 10 # setter called # c.radius = -3 # ValueError del c.area # deleter called

Benefits: Validation, computed values, lazy evaluation, clean API.

2.7 Class Methods, Static Methods, @classmethod, @staticmethod

  • @classmethod → receives class (cls) instead of instance (self)

  • @staticmethod → no self or cls — regular function in class namespace

Python

class Employee: raise_amount = 1.10 # class attribute def init(self, name, salary): self.name = name self.salary = salary @classmethod def set_raise_amount(cls, amount): cls.raise_amount = amount @staticmethod def is_workday(day): # Monday=0 ... Sunday=6 return day.weekday() < 5 def apply_raise(self): self.salary *= Employee.raise_amount Employee.set_raise_amount(1.15) # class method import datetime today = datetime.date(2026, 3, 5) # Thursday print(Employee.is_workday(today)) # True

Use @classmethod for alternative constructors, factory methods. Use @staticmethod for utility functions related to class.

2.8 Multiple Inheritance & Method Resolution Order (MRO)

Python supports multiple inheritance.

Python

class A: def show(self): print("A") class B(A): def show(self): print("B") class C(A): def show(self): print("C") class D(B, C): pass d = D() d.show() # B print(D.mro()) # [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, ...]

MRO (Method Resolution Order) → C3 linearization Use ClassName.mro() or ClassName.__mro__ to see order.

super() in multiple inheritance works beautifully with MRO.

2.9 Abstract Base Classes (abc module)

Force subclasses to implement methods.

Python

from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Rectangle(Shape): def init(self, length, width): self.length = length self.width = width def area(self): return self.length self.width def perimeter(self): return 2 (self.length + self.width) # s = Shape() # TypeError: Can't instantiate abstract class r = Rectangle(10, 5) print(r.area()) # 50

Use when: Defining interfaces or templates that must be followed.

2.10 Composition vs Inheritance – When to Use What

Inheritance ("is-a" relationship) → Dog is a Animal

Composition ("has-a" relationship) → Car has a Engine

Python

# Inheritance (is-a) class Car(Vehicle): ... # Composition (has-a) – usually preferred class Car: def init(self): self.engine = Engine() self.wheels = [Wheel() for _ in range(4)] def start(self): self.engine.start()

Rule of thumb (2026 best practice):

  • Prefer composition over inheritance (composition gives more flexibility)

  • Use inheritance only when there is a clear is-a relationship and you want to reuse behavior

  • "Favor composition over inheritance" – Gang of Four Design Patterns

Mini Project – Bank System (OOP in action)

Python

from abc import ABC, abstractmethod class Account(ABC): def init(self, account_number, balance=0): self.account_number = account_number self._balance = balance @property def balance(self): return self._balance @abstractmethod def withdraw(self, amount): pass def deposit(self, amount): if amount > 0: self._balance += amount return True return False class SavingsAccount(Account): INTEREST_RATE = 0.04 def withdraw(self, amount): if amount <= self._balance: self._balance -= amount return True return False def add_interest(self): self._balance += self._balance * SavingsAccount.INTEREST_RATE

This completes the full OOP in Depth section — now you can build clean, scalable, professional object-oriented systems!!

📚 Amazon Book Library

All my books are FREE on Amazon Kindle Unlimited🌍 Exclusive Country-Wise Amazon Book Library – Only Here!

On GlobalCodeMaster.com you’ll find complete, ready-to-use lists of my books with direct Amazon links for every country.
Belong to India, Australia, USA, UK, Canada or any other country? Just click your country’s link and enjoy:
Any eBook FREE on Kindle Unlimited ✅ Or buy at incredibly low prices
400+ fresh books written in 2025-2026 with today’s latest AI, Python, Machine Learning & tech trends – nowhere else will you find this complete country-wise collection on one platform!
Choose your country below and start reading instantly 🚀
BOOK LIBRARY USA 2026 LINK
BOOK LIBRARY INDIA 2026 LINK
BOOK LIBRARY AUSTRALIA 2026 LINK
BOOK LIBRARY CANADA 2026 LINK
BOOK LIBRARY UNITED KINGDOM 2026 LINK
BOOK LIBRARY GERMANY 2026 LINK
BOOK LIBRARY FRANCE 2026 LINK
BOOK LIBRARY ITALY 2026 LINK
BOOK LIBRARY SPAIN 2026 LINK
BOOK LIBRARY NETHERLANDS 2026 LINK
BOOK LIBRARY BRAZIL 2026 LINK
BOOK LIBRARY MEXICO 2026 LINK
BOOK LIBRARY JAPAN 2026 LINK
BOOK LIBRARY POLAND 2026 LINK
BOOK LIBRARY IRELAND 2026 LINK
BOOK LIBRARY SWEDEN 2026 LINK
BOOK LIBRARY BELGIUM 2026 LINK