liveBook · Manning

Polymorphism

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

Polymorphism is an object-oriented technique in which the same method call can produce different behavior depending on the object's class or runtime type.

A drawing window may contain rectangles, squares, and circles. Its drawing code should not need a separate loop for each kind of shape. Polymorphism lets it call the same method on every object while each object supplies the appropriate behavior. section 4.1.4

The shapes share an IS-A relationship with Shape. Shape declares an abstract draw() method with no drawing behavior. Rectangle implements draw(); Square inherits Rectangle’s implementation, with its height and width constrained to make a square; Circle supplies its own implementation. The shared method name lets the display treat them all as shapes without ignoring their differences. section 4.1.4

def on_draw(self):
 
    # Clear the screen and start drawing
    arcade.start_render()
 
    # Draw the rectangles
    for shape in self.shapes:
        shape.draw()

The display loops over its shapes and calls shape.draw() for each one. The loop stays the same whether the next object is a rectangle, square, or circle. section 4.1.4

This is useful when a collection contains different kinds of object that share an operation. Another shape derived from Shape can join the drawing loop so long as it supports a draw() method that renders it. The display remains focused on when to draw; each shape remains responsible for how it draws. section 4.1.4

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Defines polymorphism and works through inherited and shape-specific draw() methods; stops short of method-dispatch internals.
Examples
Uses Rectangle, Square, and Circle objects in a drawing window, plus a loop that calls draw() on each shape.
What it assumes
Assumes familiarity with classes, methods, inheritance, and iteration over a list.
What you can do after
Apply it via Python classes to draw a mixed collection of shapes without changing the display loop for each shape.
How it connects
Connects inheritance, class hierarchies, abstract methods, and IS-A relationships to a shared drawing operation.

Also explained in

Compare how 9 books explain polymorphism →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.