Skip to content

Instantly share code, notes, and snippets.

@joelburton
Created September 25, 2018 22:08
Show Gist options
  • Save joelburton/1a6b8f69cb05c61ed8dcf275d02e0aea to your computer and use it in GitHub Desktop.
Save joelburton/1a6b8f69cb05c61ed8dcf275d02e0aea to your computer and use it in GitHub Desktop.
polymorphism
# Imagine with have some classes for animals:
class Animal:
"""Base class for all animals."""
def __init__(self, name):
self.name = name
class Dog(Animal):
"""Dogs."""
def bark(self):
return "woof! barf bark!"
class Cat(Animal):
"""Cats."""
def meow(self):
return "meow, purr purr"
class Duck(Animal):
"""Ducks."""
def quack(self):
return "quack! quack!"
# Let's make some animals
fido = Dog("Fido")
fluffy = Cat("Fluffy")
crumbs = Duck("Crumbs")
# And put them all into a petting zoo
zoo = [fido, fluffy, crumbs]
# Now, we want each animal to make noise, in order. However, each
# class uses a *similar-in-theory* but *differently-named* method
to make noise. So our code would have to be, ugh:
for animal in zoo:
if isinstance(animal, Dog):
animal.bark()
elif isinstance(animal, Cat):
animal.meow()
elif isinstance(animal, Duck):
animal.quack()
# This works, but it's hairy -- especially if we needed to add more
# types of animals (we'd have to change the inside of the for-loop!)
# These methods (bark, meow, quack) all mean basically the same thing:
# "make noise in the right way for this kind of animal".
# Much better, therefore, is to give them the same name:
class Dog(Animal):
"""Dogs."""
def speak(self):
return "woof! barf bark!"
class Cat(Animal):
"""Cats."""
def speak(self):
return "meow, purr purr"
class Duck(Animal):
"""Ducks."""
def speak(self):
return "quack! quack!"
# Now our for-loop is much simpler:
for animal in zoo:
animal.speak()
# That's "polymorphism": different objects from different classes
# can be used interchangeably. When possible, designing your classes
# to be "polymorphic" is good. For example, if you were building a
# special kind of list, similar-but-different from Python's List type,
# you be smart to make as interoperable as possible with a standard
# list by using the same method names ("append", "pop", etc),
# as was sensible
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment