Have two classes begun to repeat the same attributes and methods? Inheritance lets a subclass reuse a superclass’s implementation while adding behavior for a more specific role. Move genuinely shared functionality into the superclass, but justify the hierarchy first: managing related classes can be harder than keeping separate ones. section 8.5 section 8.5.1
Reuse an employee class
class Employee: def __init__(self, name, employee_id): self.name = name self.employee_id = employee_id def login(self): print(f"An employee {self.name} just logged in.") class Supervisor(Employee): pass supervisor = Supervisor("John", "1001") print(supervisor.name) # John supervisor.login() # An employee John just logged in. Put the superclass in parentheses after the subclass name. Even with only pass in its body, Supervisor inherits Employee’s initializer and login method. Add subclass-specific implementations only where the roles differ. section 8.5.2 section 8.5
A hierarchy can also be designed top-down, starting with a general class and adding specialized models. More often, similarities emerge among existing classes; extracting their shared behavior then reduces repetition. Keep distinct behavior in the subclasses rather than forcing every role into the superclass. section 8.5.1 section 8.6
Inherit data-class fields
@dataclass class BaseBill: meal_amount: float @dataclass class TippedBill(BaseBill): tip_amount: float print(TippedBill(60, 10)) # TippedBill(meal_amount=60, tip_amount=10) Decorate both classes. The subclass constructor takes inherited fields first, followed by its own. If a superclass field has a default, subclass fields must also have defaults; otherwise construction fails with a non-default-argument error. Avoid superclass defaults when subclasses need that flexibility. section 9.2.4
Inheritance also matters when using objects:
- Prefer isinstance(obj, Superclass) for a check that should accept subclass instances. Unlike an exact comparison with type(obj), it accounts for inheritance. section 10.1.2
- A built-in class can be a superclass: an int subclass can override __new__ to convert card labels into values used as a sorted key. section 10.5.3


















