Python Classes: Attributes, Methods, and Inheritance
What you’ll learn
Section titled “What you’ll learn”By the end of this tutorial you will be able to define a class with attributes and methods, create instances, use __init__ correctly, and build a simple inheritance hierarchy.
Prerequisites
Section titled “Prerequisites”- Python 3.9+ installed
- Familiarity with functions and variables (variables tutorial, functions tutorial)
What is a class?
Section titled “What is a class?”A class is a template for creating objects that bundle data (attributes) and behavior (methods) together. An object (or instance) is one concrete thing built from that template.
The analogy: a class is a cookie cutter; instances are the cookies. All cookies have the same shape but different decorations.
Step 1 — Define a basic class
Section titled “Step 1 — Define a basic class”Save as orders.py and run with python orders.py (Python 3.9+):
class Order: """Represents a customer order."""
def __init__(self, order_id: str, customer: str, amount: float) -> None: # Instance attributes: unique to each object self.order_id = order_id self.customer = customer self.amount = amount self.status = "pending"
def confirm(self) -> None: """Mark the order as confirmed.""" self.status = "confirmed" print(f"Order {self.order_id} confirmed.")
def total_with_tax(self, tax_rate: float = 0.08) -> float: """Return amount plus tax.""" return round(self.amount * (1 + tax_rate), 2)
def __str__(self) -> str: """Human-readable representation.""" return f"Order({self.order_id}, {self.customer}, {self.status})"
# Create instancesorder1 = Order("ORD-001", "BensonCo", 100.0)order2 = Order("ORD-002", "NovaCorp", 250.0)
print(order1) # Order(ORD-001, BensonCo, pending)print(order1.total_with_tax()) # 108.0order1.confirm() # Order ORD-001 confirmed.print(order1.status) # confirmedprint(order2.status) # pending — order2 is unaffectedKey points:
__init__runs automatically when you callOrder(...). It initializes instance attributes.selfis the first parameter of every instance method. Python passes it automatically — you never pass it yourself.- Each instance (
order1,order2) has its own copy oforder_id,customer,amount, andstatus.
Step 2 — Class attributes vs instance attributes
Section titled “Step 2 — Class attributes vs instance attributes”A class attribute is shared by all instances. An instance attribute belongs to one object.
class Order: # Class attribute — shared tax_rate: float = 0.08 order_count: int = 0
def __init__(self, order_id: str, amount: float) -> None: # Instance attributes — unique per object self.order_id = order_id self.amount = amount Order.order_count += 1 # modify via the class name, not self
def total(self) -> float: return round(self.amount * (1 + Order.tax_rate), 2)
o1 = Order("ORD-001", 100.0)o2 = Order("ORD-002", 200.0)
print(Order.order_count) # 2 — shared across all instancesprint(o1.tax_rate) # 0.08 — accessed on instance, reads class attrprint(o1.total()) # 108.0Warning: If you write self.tax_rate = 0.05, you create a new instance attribute that shadows the class attribute for that instance only. The class attribute is unchanged. Use ClassName.attribute = ... to modify a class attribute.
Step 3 — Class methods and static methods
Section titled “Step 3 — Class methods and static methods”class Order: tax_rate: float = 0.08
def __init__(self, order_id: str, amount: float) -> None: self.order_id = order_id self.amount = amount
# Regular method: operates on a specific instance def total(self) -> float: return round(self.amount * (1 + self.tax_rate), 2)
# Class method: operates on the class, not an instance @classmethod def set_tax_rate(cls, rate: float) -> None: cls.tax_rate = rate
# Static method: neither instance nor class — a utility function @staticmethod def is_valid_order_id(order_id: str) -> bool: return order_id.startswith("ORD-") and len(order_id) > 4
Order.set_tax_rate(0.10) # changes tax for all future instancesprint(Order.is_valid_order_id("ORD-001")) # Trueprint(Order.is_valid_order_id("XXX")) # FalseStep 4 — Inheritance
Section titled “Step 4 — Inheritance”A subclass inherits all attributes and methods from its parent and can override or extend them.
class Order: def __init__(self, order_id: str, amount: float) -> None: self.order_id = order_id self.amount = amount self.status = "pending"
def total(self) -> float: return round(self.amount * 1.08, 2)
def __str__(self) -> str: return f"Order({self.order_id}, {self.status})"
class DigitalOrder(Order): """An order for a digital product — no shipping required."""
def __init__(self, order_id: str, amount: float, download_url: str) -> None: super().__init__(order_id, amount) # call the parent __init__ self.download_url = download_url self.status = "ready"
def fulfill(self) -> str: return f"Download at: {self.download_url}"
def __str__(self) -> str: return f"DigitalOrder({self.order_id}, {self.download_url})"
d = DigitalOrder("ORD-010", 29.99, "https://downloads.example.test/product-01")print(d.total()) # 32.39 — inherited from Orderprint(d.fulfill()) # Download at: https://...print(isinstance(d, Order)) # Trueprint(isinstance(d, DigitalOrder)) # Truesuper().__init__(...) calls the parent class’s __init__. Always call super().__init__ in a subclass __init__ unless you have a specific reason not to.
Step 5 — Dunder methods for operator support
Section titled “Step 5 — Dunder methods for operator support”Python uses dunder methods (double-underscore methods) to integrate with built-in operations:
class OrderBatch: def __init__(self, orders: list) -> None: self._orders = list(orders)
def __len__(self) -> int: return len(self._orders)
def __getitem__(self, index: int): return self._orders[index]
def __iter__(self): return iter(self._orders)
def __repr__(self) -> str: return f"OrderBatch({len(self._orders)} orders)"
batch = OrderBatch([Order("ORD-001", 100), Order("ORD-002", 200)])print(len(batch)) # 2print(batch[0]) # Order(ORD-001, pending)for order in batch: print(order.order_id)Complete working example
Section titled “Complete working example”from dataclasses import dataclass
@dataclassclass Product: sku: str name: str price: float
@dataclassclass OrderLine: product: Product quantity: int
def line_total(self) -> float: return round(self.product.price * self.quantity, 2)
class Order: def __init__(self, order_id: str, customer: str) -> None: self.order_id = order_id self.customer = customer self.lines: list[OrderLine] = []
def add_line(self, product: Product, qty: int) -> None: self.lines.append(OrderLine(product, qty))
def subtotal(self) -> float: return round(sum(line.line_total() for line in self.lines), 2)
def total(self, tax_rate: float = 0.08) -> float: return round(self.subtotal() * (1 + tax_rate), 2)
def __str__(self) -> str: return f"Order {self.order_id} for {self.customer}: ${self.total():.2f}"
widget = Product("WIDGET-01", "Widget", 29.99)gadget = Product("GADGET-01", "Gadget", 49.99)
order = Order("ORD-001", "BensonCo")order.add_line(widget, 3)order.add_line(gadget, 1)
print(order) # Order ORD-001 for BensonCo: $146.87print(order.subtotal()) # 139.96Run with python orders.py (Python 3.9+). Expected output: Order ORD-001 for BensonCo: $146.87 and 139.96.
Common mistakes
Section titled “Common mistakes”- Forgetting
selfas the first parameter. A method withoutselfis a function at the class namespace level and cannot access instance data. - Calling
super().__init__without arguments. Pass all required arguments:super().__init__(order_id, amount). - Mutable default in
__init__:def __init__(self, items=[]). The list is shared across all instances. Useitems=Noneand assignself.items = items or []inside the body.
Next steps
Section titled “Next steps”- OOP in depth — properties, dunder methods, multiple inheritance
- Dataclasses —
@dataclassfor data-holding classes - Magic methods — full dunder method reference
Official references
Section titled “Official references”- Python docs: Classes
- Python docs: Data model — dunder methods