Lesson 12 of 14 · 12 min

Classes

A class is a blueprint for objects that share the same data and behaviour:

class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []

    def learn(self, trick):
        self.tricks.append(trick)

    def __str__(self):
        return f"{self.name} knows {len(self.tricks)} tricks"


rex = Dog("Rex")
rex.learn("sit")
print(rex)          # Rex knows 1 tricks
  • __init__ runs when you create an object with Dog("Rex"). It sets up the object's data.
  • self is the object itself. Every method takes it as its first parameter.
  • self.name = name stores a value on that particular dog.
  • __str__ controls what print and str() show.

Inheritance

A class can build on another, keeping its methods and changing or adding some:

class GuideDog(Dog):
    def __init__(self, name, owner):
        super().__init__(name)      # run Dog's setup first
        self.owner = owner

    def __str__(self):
        return f"{super().__str__()} and guides {self.owner}"

super() reaches the parent class, so you can reuse its code instead of copying it.

Your task

  1. class Product with:
    • __init__(self, name, price), starting stock at 0,
    • restock(self, quantity),
    • sell(self, quantity): raises ValueError if there is not enough stock; otherwise reduces stock and returns price * quantity,
    • __str__: "Rice (4 in stock)".
  2. class DiscountedProduct(Product) with an extra discount (e.g. 0.2 for 20%), whose sell returns the discounted total.
main.py
class Product:
    def __init__(self, name, price):
        pass


# class DiscountedProduct(Product): ...


soap = Product("Soap", 2.5)

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…