๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 9 of 40
Lesson 9 of 40 OOP Intermediate โฑ 35 min

Classes & OOP Fundamentals

Build models with Python classes โ€” instance and class variables, __init__, properties, dunder methods, and Pythonic object design.

Part 1: Defining a Class

class BankAccount:
    """A simple bank account."""
    interest_rate = 0.05 # class variable

    def __init__(self, owner: str, balance: float = 0.0):
        self.owner = owner # instance variable
        self._balance = balance # _ = "private by convention"

    @property
    def balance(self) -> float:
        return self._balance

    def deposit(self, amount: float):
        if amount <= 0: raise ValueError("Positive amount required")
        self._balance += amount

Part 2: Dunder (Magic) Methods

class Vector:
    def __init__(self, x:float, y:float):
        self.x, self.y = x, y
    def __repr__(self): return f"Vector({self.x}, {self.y})"
    def __add__(self, other): return Vector(self.x+other.x, self.y+other.y)
    def __len__(self): return int((self.x**2+self.y**2)**0.5)
    def __eq__(self, other): return (self.x,self.y) == (other.x,other.y)

Part 3: @classmethod & @staticmethod

class User:
    def __init__(self, name, email):
        self.name, self.email = name, email

    @classmethod
    def from_dict(cls, data: dict) -> "User":
        return cls(data["name"], data["email"])

    @staticmethod
    def validate_email(email: str) -> bool:
        return "@" in email

Part 4: __slots__ for Memory Efficiency

class Point:
    __slots__ = ("x", "y") # no __dict__ โ€” saves ~50% memory
    def __init__(self, x:float, y:float):
        self.x, self.y = x, y

# Creating millions of points is now much faster
points = [Point(i, i**2) for i in range(1_000_000)]