Python Polymorphism Relies on Duck Typing, Not on a Shared Parent Class
Object-oriented programming rests on objects that bundle state (what they are) and behaviour (what they do), with four ideas around them: encapsulation, abstraction, inheritance and polymorphism. In Python, polymorphism (one call working on many kinds of objects) doesn't need inheritance: any object with the right method can be used, whatever its class. Inheritance is for sharing code; polymorphism is about sharing an interface, and the two are often confused.
Inheritance Shares Code, Overriding Changes It
class Animal:
def __init__(self, name: str):
self.name = name
def sleep(self) -> str:
return f"{self.name} is sleeping."
class Dog(Animal): # Dog inherits name and sleep()
def sleep(self) -> str: # overriding replaces the parent's version
return f"{self.name} is sleeping by the door."
A method that needs the instance's attributes must go through self: f"{domestic_name}" instead of f"{self.domestic_name}" raises NameError at call time.
Polymorphism Works Without a Common Parent
class Robot:
def __init__(self, name: str):
self.name = name
def sleep(self) -> str:
return f"{self.name} is in standby."
for thing in (Dog("Rex"), Robot("R2")):
print(thing.sleep()) # each object answers in its own way
Robot has no relation to Animal; the loop only needs a sleep() method ("if it walks like a duck…"). Go reaches the same result with interfaces satisfied implicitly.
Abstraction Hides How, Shows What
Callers use car.presentation() without knowing how it builds the text. When subclasses must provide a method, an abstract base class makes it explicit:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
Shape() can't be instantiated, and a subclass that forgets area() fails when created rather than when called.
References
- Programming Languages MOC - hub for language notes.
- Python Double-Underscore Attributes Are Name-Mangled, Not Private - encapsulation, the fourth idea.
- Go Interfaces Are Satisfied Implicitly by Having the Methods - the same structural idea in Go.
- Python documentation: Classes, inheritance - inheritance and method overriding.
- Python documentation: abc - abstract base classes.
Review cards
Flashcard What does making Shape an abstract base class with @abstractmethod area() change?
Shape itself can't be instantiated, and a subclass that doesn't implement area() fails when it is created, not later when area() is called.