🌱 Junior Track 11 of 11

11. Object-Oriented Programming (OOP)

Master essential Python OOP: `Classes`, `Objects`, `self`, `__init__`, `Instance vs Class Variables`, `@classmethod`, `@staticmethod`, `Inheritance`, `super()`, the `4 Pillars of OOP`, and essential `Dunder Methods` (`__str__`, `__repr__`, `__len__`, `__eq__`, `__lt__`, `__iter__`, `__next__`).

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 11 — OBJECT-ORIENTED PROGRAMMING (OOP)
# ==============================================================================

from abc import ABC, abstractmethod

# 1. Base Abstraction & Inheritance
class Employee(ABC):
    """Abstract Base Class demonstrating Encapsulation & Class variables."""
    company_name: str = "TeachCloud Technologies"  # Class Variable

    def __init__(self, name: str, salary: float):
        self.name = name                 # Public Instance Variable
        self._salary = salary            # Protected Instance Variable

    @property
    def salary(self) -> float:
        """Encapsulation: Getter for salary."""
        return self._salary

    @abstractmethod
    def calculate_bonus(self) -> float:
        """Abstraction: Must be implemented by child classes."""
        pass

    @classmethod
    def get_company(cls) -> str:
        """Class Method operating on class state."""
        return cls.company_name

    @staticmethod
    def is_valid_salary(amount: float) -> bool:
        """Static Method independently validating utility data."""
        return amount > 0

# 2. Child Class with Dunder Methods
class Developer(Employee):
    def __init__(self, name: str, salary: float, skills: list[str]):
        super().__init__(name, salary)  # Invoke parent constructor with super()
        self.skills = skills

    def calculate_bonus(self) -> float:
        # Polymorphism & Method Overriding
        return self.salary * 0.15

    # Dunder Methods Implementation
    def __str__(self) -> str:
        return f"Developer({self.name}, ${self.salary:,.2f})"

    def __repr__(self) -> str:
        return f"Developer(name='{self.name}', salary={self.salary})"

    def __len__(self) -> int:
        return len(self.skills)

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Developer):
            return self.salary == other.salary
        return False

    def __lt__(self, other: "Developer") -> bool:
        return self.salary < other.salary

if __name__ == "__main__":
    dev1 = Developer("Dilshad", 95000.0, ["Python", "Flask", "SQL"])
    dev2 = Developer("Alex", 85000.0, ["JavaScript", "HTML"])

    print(f"Company: {Developer.get_company()}")
    print(f"Developer Profile: {dev1}")
    print(f"Skill Count (__len__): {len(dev1)}")
    print(f"Bonus Calculation: ${dev1.calculate_bonus():,.2f}")
    print(f"Salary Comparison (dev1 > dev2): {dev1 > dev2}")

⭐ Rate Track 11: Object-Oriented Programming (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
🌱 Junior Track 11 Master Reference

11. Python Object-Oriented Programming (OOP) Essentials

1️⃣ Classes, Objects, Attributes, `self` & `__init__`

A Class is a blueprint for creating objects. An Object is a concrete instance of that class. The __init__ method initializes object attributes when instantiated, and self represents the instance invoking the method.

class User:
    def __init__(self, username):
        self.username = username # Instance variable

2️⃣ Instance vs. Class Variables & Method Types

Instance variables are unique to each object. Class variables are shared across all instances.

  • Instance Method: Takes self as first parameter; operates on instance data.
  • Class Method (`@classmethod`): Takes cls as first parameter; operates on class state.
  • Static Method (`@staticmethod`): Takes no mandatory self/cls; utility function bound to namespace.

3️⃣ Inheritance, Multiple Inheritance & `super()`

Child classes inherit attributes and methods from parent classes. Use super().__init__() to invoke parent constructors safely. Python also supports Multiple Inheritance (`class Child(ParentA, ParentB)`).

class AdminUser(User):
    def __init__(self, username, role="Admin"):
        super().__init__(username)
        self.role = role

4️⃣ Composition vs. Inheritance

Inheritance ("is-a"): A Developer is an Employee.
Composition ("has-a"): A Car has an Engine object as an attribute. Composition increases code flexibility and reduces tight coupling.

5️⃣ Special / Dunder Methods Reference Matrix

Dunder Method Triggered By Description & Use Case
__init__(self, ...) User("Dilshad") Constructor method initializing instance attributes.
__str__(self) str(obj) or print(obj) User-friendly string representation.
__repr__(self) repr(obj) or REPL terminal Developer unambiguous string representation for debugging.
__len__(self) len(obj) Returns collection or dataset size integer.
__eq__(self, other) obj1 == obj2 Custom equality comparison logic.
__lt__(self, other) obj1 < obj2 Less-than comparison enabling sorting with sorted().
__iter__ / __next__ for item in obj: Makes custom class objects iterable sequences.
← 10. Scope & Namespaces 🌱 Junior Hub 12. Exceptions →