Skip to main content

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
  • class keyword introduces the definition.
  • Methods accept self as 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 @property to create computed attributes with read-only semantics.

Next up in your learning path