liveBook · Manning

Virtual method

As explained in The Quick Python Book, Fourth Edition

A virtual method is a method whose implementation can be dynamically selected according to the class of the object on which it is invoked.

A virtual method is selected dynamically from the object's class hierarchy. In Python, every method is virtual: if the current class does not define it, Python searches superclasses and uses the first matching implementation. section 15.6 section 15.15

The practical rules are:

  • Inherit a method simply by defining a subclass without replacing that method. section 15.6
  • Override a method by defining a method with the same name in the subclass; calls then use the subclass implementation. section 15.15
  • Use virtual dispatch to share behavior across related classes while allowing specialized subclasses to replace it. section 15.6

Inherited movement

A Circle can use Shape.move even though Circle does not define move. Calling c.move(3, 4) updates the inherited coordinates and produces c.x = 3, c.y = 4. section 15.6

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines dynamic method lookup and inheritance, but stops short of implementation-level dispatch details.
Examples
Demonstrates inherited movement through Shape, Circle, coordinates, and a concrete c.move(3, 4) call.
What it assumes
Assumes familiarity with classes, instances, methods, and inheritance; explains virtual lookup through those constructs.
What you can do after
Evaluate inherited method behavior by tracing subclass and superclass lookup in small Python class hierarchies.
How it connects
Connects virtual methods to inheritance, subclasses, superclasses, method overriding, and class design.

Also explained in

Compare how 3 books explain virtual method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.