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

3. Encapsulation – Data Hiding and Protection

Encapsulation is one of the four pillars of OOP. It means bundling data (attributes) and methods that operate on that data into a single unit (class), while restricting direct access to some of the object's internal details.

Main goals of encapsulation:

  • Hide internal implementation details

  • Protect data from accidental or invalid changes

  • Provide controlled access through methods (getters/setters)

Python does not enforce strict private members like Java or C++ — it follows a "we are all consenting adults" philosophy. Instead, it uses naming conventions to signal privacy.

3.1 Public, Protected (_single underscore) and Private (__double underscore) Members

Python uses naming conventions to indicate access level:

Access LevelNaming ConventionMeaning / ConventionCan be accessed from outside?ExamplePublicNormal name (no underscore)Intended to be used freely by anyoneYesself.name, self.get_info()ProtectedSingle underscore prefix"Internal use" – should not be accessed directly from outside (convention only)Technically yes, but discouragedself._balance, self._calculate_interest()PrivateDouble underscore prefixName mangling applied — strongly discourages external access (but still possible)Hard to access directlyself.__secret_pin, self.__validate()

Code Example

Python

class BankAccount: def init(self, owner, balance=0): self.owner = owner # public self._balance = balance # protected (by convention) self.__pin = 1234 # private (name mangled) def deposit(self, amount): if amount > 0: self._balance += amount print(f"Deposited ₹{amount}. New balance: ₹{self._balance}") else: print("Amount must be positive") def get_balance(self): return self._balance def internalcheck(self): # protected method print("Internal balance check...") def __validate_pin(self, pin): # private method return pin == self.__pin acc = BankAccount("Anshuman", 5000) print(acc.owner) # Anshuman (public – OK) print(acc._balance) # 5000 (protected – works but not recommended) acc.deposit(2000) # Deposited ₹2000. New balance: ₹7000 # print(acc.__pin) # AttributeError – cannot access directly

Important:

  • _single → "Please don't touch this unless you really know what you're doing"

  • __double → "Strongly discourages direct access" (but see name mangling below)

3.2 Name Mangling – How Python Implements “Private”

When you use __double_underscore prefix, Python performs name mangling — it automatically changes the attribute name to make it harder to access from outside the class.

How name mangling works:

  • __secret inside class BankAccount becomes BankAccount_secret

Example

Python

class BankAccount: def init(self, pin): self.__pin = pin # will be mangled to BankAccount_pin acc = BankAccount(4321) # This fails: # print(acc.__pin) # AttributeError # This works (but never do this in real code!): print(acc._BankAccount__pin) # 4321

Purpose of name mangling:

  • Prevents accidental name conflicts in subclasses

  • Strongly signals: "This is internal — don't touch it"

  • Still allows access if you really need it (for debugging or advanced use)

Best practice: Never access mangled names directly in normal code — use public methods instead.

3.3 @property, @setter, @deleter – Pythonic Getter-Setter Methods

Python provides a clean, elegant way to control access to attributes using properties. This lets you use attributes like normal variables, but with validation, computation, or logging behind the scenes.

Basic property example

Python

class Circle: def init(self, radius): self._radius = radius # protected storage @property def radius(self): # getter return self._radius @radius.setter def radius(self, value): # setter if value < 0: raise ValueError("Radius cannot be negative") self._radius = value @property def area(self): # read-only computed property return 3.14159 self._radius * 2 c = Circle(5) print(c.radius) # 5 ← looks like attribute, but calls getter print(c.area) # 78.53975 ← computed on the fly c.radius = 10 # calls setter # c.radius = -3 # ValueError # c.area = 100 # AttributeError – no setter defined (read-only)

With @deleter (rare but useful)

Python

class TempFile: def init(self, path): self._path = path @property def path(self): return self._path @path.deleter def path(self): print(f"Deleting temporary file: {self._path}") # os.remove(self._path) # real deletion self._path = None tf = TempFile("temp.txt") del tf.path # calls deleter → "Deleting temporary file: temp.txt"

Why use properties instead of old-style getters/setters?

  • Looks like normal attribute access (c.radius instead of c.get_radius())

  • Allows validation, computation, logging without changing interface

  • Backward compatible – you can start with public attribute and later add @property without breaking code

Mini Summary Project – Secure Bank Account

Python

class SecureBankAccount: def init(self, owner, initial_balance=0): self.owner = owner self._balance = initial_balance self.__pin = 1234 # private @property def balance(self): return self._balance @balance.setter def balance(self, value): raise AttributeError("Direct balance modification not allowed. Use deposit/withdraw.") def deposit(self, amount, pin): if pin != self.__pin: raise ValueError("Incorrect PIN") if amount <= 0: raise ValueError("Amount must be positive") self._balance += amount print(f"Deposited ₹{amount}. New balance: ₹{self._balance}") acc = SecureBankAccount("Anshuman", 10000) acc.deposit(5000, 1234) # success print(acc.balance) # 15000 # acc.balance = 0 # AttributeError

This completes the full Encapsulation – Data Hiding and Protection section — now you understand how to protect data while keeping code clean and Pythonic!

📚 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