Suppose a task-management application has several kinds of employees. If their classes repeat the same attributes and methods, where should that shared code live? Put it in an Employee superclass, then define specialized subclasses. A superclass supplies behavior its subclasses can reuse; inheritance is most useful when the shared behavior justifies the added relationship between classes. section 8.5 section 8.5.1
Inherit shared behavior
Name the superclass in parentheses after the subclass name: 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. Even with only pass in its body, Supervisor can use Employee’s initializer and login method. section 8.5.2
A subclass can replace an inherited method by defining one with the same name. It can also extend behavior: a Supervisor.logout method can call super().logout() before performing additional supervisor actions. For a method call, Python searches the subclass first, then its superclass, then object in this single-inheritance example. Inspect that order with Supervisor.mro(). section 8.5.3
Keep the hierarchy useful rather than merely possible:
- Start with separate classes when their relationship is unclear. Extract a superclass when substantial shared functionality appears; maintaining that functionality in one place reduces repetition, but subclasses become coupled to it. section 8.5.1 section 8.5.5
- Use a protected method, named with one leading underscore, when subclasses need access to nonpublic behavior. A double-underscore private name is mangled, so a subclass cannot call it directly under that name. section 8.5.4
- When checking whether an object belongs to a superclass hierarchy, use isinstance: unlike an immediate-class comparison with type, it also accepts subclass instances. section 10.1.2
Data classes can also have superclasses. A data-class subclass receives the superclass’s fields before its own fields in the generated constructor. Because fields without defaults must precede fields with defaults, a default-valued superclass field requires default values for added subclass fields; leaving superclass fields without defaults preserves more flexibility. section 9.2.4









