Index Ai Academy
Phase 0 · ToolsPython core

Inheritance and class attributes

About 35 minLooking ahead: some prerequisites aren't done yet

Why this matters

From the deep learning phase on, nearly every model you write starts with class MyModel(nn.Module): and calls super().__init__(). That's inheritance: your class gets everything PyTorch's Module knows, and you add your own parts. Libraries everywhere work this way, from web frameworks to custom error types, so reading and writing it is part of using Python at all.

  • Tell class attributes, shared by every object, from attributes each object owns
  • Build a class on another with inheritance, and extend its methods with super()
  • Override a method so each kind of object behaves its own way
  • Choose between inheriting from a class and keeping an object of it inside yours

Shared by every object: class attributes

So far, every attribute you've made lived on one object: self.name = name gives each object its own name. An attribute written in the class body, outside any method, belongs to the class itself. Every object of the class shares it:

class Product:
    TAX_RATE = 0.08
    made = 0

    def __init__(self, name, price):
        self.name = name
        self.price = price
        Product.made = Product.made + 1

    def price_with_tax(self):
        return round(self.price * (1 + self.TAX_RATE), 2)

tent = Product("Ridgeline tent", 289)
mug = Product("Trail mug", 14)
print(tent.price_with_tax(), mug.price_with_tax())
print(Product.made, Product.TAX_RATE)

TAX_RATE is written once and every product uses it. Change Product.TAX_RATE and every product sees the new rate. made counts how many products were created, so each __init__ adds one to Product.made.

Use class attributes for values that really are the same for every object: settings, limits, counters. Upper-case names like TAX_RATE say "this is a constant; don't change it".