Python Classes Explained
OOP Core
Defining Classes in Python
Classes package related data and behavior. Master syntax, attributes, and method definitions here.
Basics
class Invoice:
currency = "USD" # class attribute
def __init__(self, total: float, customer: str):
self.total = total
self.customer = customer
def apply_discount(self, percent: float) -> None:
self.total *= 1 - percent
classkeyword introduces the definition.- Methods accept
selfas the first argument (the instance). - Use docstrings to describe purpose and parameters.
Attributes
- Instance attributes live on each object (
self.total). - Class attributes live on the class itself and are shared unless overridden.
- Leverage
@propertyto create computed attributes with read-only semantics.