liveBook · Manning

Override

As explained in Python How-To

Method overriding is the object-oriented technique in which a subclass defines a method with the same name as an inherited method to provide a specialized implementation.

Override means defining a method in a subclass with the same name as an inherited method, but with a specialized implementation. Python also treats implementations of special methods such as __init__ and __str__ as overrides because every class ultimately inherits from object. section 8.4

Use overriding when a subclass needs behavior different from its superclass. Python does not require an override keyword: defining the same method name is sufficient. section 8.5.3

Apply overriding in several practical ways:

  • Replace a superclass method completely with a subclass-specific implementation. section 8.5.3
  • Extend inherited behavior by calling super().method() and then adding subclass-specific actions. section 8.5.3
  • Customize an instance's displayed text by overriding __str__; return a descriptive str containing useful attributes. section 8.4.1
  • Inspect method resolution order with Class.mro() when inheritance determines which implementation a method call uses. section 8.5.3

Specialized supervisor behavior

class Supervisor(Employee): def login(self): print(f"A supervisor {self.name} just logged in.") supervisor = Supervisor("John", "1001") supervisor.login() # output: A supervisor John just logged in. section 8.5.3

class Supervisor(Employee):
   def logout(self):
       super().logout()
       print("Additional logout actions for a supervisor")

This listing demonstrates a partial override: the subclass preserves superclass logout behavior through super() before adding another action. section 8.5.3

How Python How-To covers it

How deep it goes
Defines complete and partial overrides, demonstrates __str__, and traces single-superclass lookup through method resolution order.
Examples
Uses Task.__str__, Supervisor.login, Supervisor.logout, super(), and Class.mro() as concrete demonstrations.
What it assumes
Assumes classes, instances, inheritance, constructors, and methods; teaches overriding through familiar Python class examples.
What you can do after
Apply overriding to replace or extend inherited methods and customize printed representations in Python classes.
How it connects
Connects inheritance, subclasses, superclasses, special methods, object, and method resolution order.

Also explained in

Compare how 3 books explain override →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.