Skip to content

Python Classes: Attributes, Methods, and Inheritance

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.

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.

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 instances
order1 = 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.0
order1.confirm() # Order ORD-001 confirmed.
print(order1.status) # confirmed
print(order2.status) # pending — order2 is unaffected

Key points:

  • __init__ runs automatically when you call Order(...). It initializes instance attributes.
  • self is the first parameter of every instance method. Python passes it automatically — you never pass it yourself.
  • Each instance (order1, order2) has its own copy of order_id, customer, amount, and status.

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 instances
print(o1.tax_rate) # 0.08 — accessed on instance, reads class attr
print(o1.total()) # 108.0

Warning: 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 instances
print(Order.is_valid_order_id("ORD-001")) # True
print(Order.is_valid_order_id("XXX")) # False

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 Order
print(d.fulfill()) # Download at: https://...
print(isinstance(d, Order)) # True
print(isinstance(d, DigitalOrder)) # True

super().__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)) # 2
print(batch[0]) # Order(ORD-001, pending)
for order in batch:
print(order.order_id)
from dataclasses import dataclass
@dataclass
class Product:
sku: str
name: str
price: float
@dataclass
class 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.87
print(order.subtotal()) # 139.96

Run with python orders.py (Python 3.9+). Expected output: Order ORD-001 for BensonCo: $146.87 and 139.96.

  • Forgetting self as the first parameter. A method without self is 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. Use items=None and assign self.items = items or [] inside the body.