Object-Oriented Programming (OOP) in Python models concepts as classes with encapsulated attributes and methods. Python uses double-underscore magic methods (dunder methods) like __init__, __str__, and __repr__ to integrate objects into core language protocols.
flowchart TD
A["Class Definition (BankAccount)"] --> B["Class Attribute (bank_name)"]
A --> C["Instance Attributes (account_id, balance)"]
A --> D["Dunder Methods (__init__, __repr__, __eq__)"]
A --> E["Instance Methods (deposit, withdraw)"]
__init__(self, ...): Instance initializer constructor.__repr__(self): Unambiguous developer string representation for debugging (repr(obj)).__str__(self): Human-readable string representation (str(obj) / print(obj)).__eq__(self, other): Equality operator overloading (==).class BankAccount:
"""Represent a customer bank account with balance guards."""
bank_name: str = "Global Tech Bank" # Class Attribute
def __init__(self, account_id: str, initial_balance: float = 0.0) -> None:
if initial_balance < 0:
raise ValueError("Initial balance cannot be negative.")
self.account_id: str = account_id # Instance Attribute
self._balance: float = initial_balance # Protected Instance Attribute
def deposit(self, amount: float) -> float:
if amount <= 0:
raise ValueError("Deposit amount must be positive.")
self._balance += amount
return self._balance
def withdraw(self, amount: float) -> float:
if amount > self._balance:
raise ValueError("Insufficient funds for withdrawal.")
self._balance -= amount
return self._balance
def __repr__(self) -> str:
return f"BankAccount(account_id={self.account_id!r}, balance={self._balance})"
def __str__(self) -> str:
return f"Account #{self.account_id} | Balance: ${self._balance:.2f}"
if __name__ == "__main__":
acc = BankAccount("ACC-1092", 500.0)
acc.deposit(250.0)
print("Developer Repr:", repr(acc))
print("User String:", str(acc))
__repr__: If you only implement one representation method, implement __repr__ because __str__ defaults to __repr__ if omitted.self Parameter: self is an explicit reference to the current object instance passed automatically by Python during method invocation._protected) to signal internal attributes, or double underscores (__private) for name-mangling.Create a class Rectangle with attributes width and height, a method area() -> float, and a __str__ method returning "Rectangle WxH".
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With