Skip to content

Instantly share code, notes, and snippets.

@aldraco
Last active September 5, 2019 21:21
Show Gist options
  • Save aldraco/199ae1de2fa0effd36cfd7a0da006ece to your computer and use it in GitHub Desktop.
Save aldraco/199ae1de2fa0effd36cfd7a0da006ece to your computer and use it in GitHub Desktop.
Ducks, quack!
# First, let's define what will end up being our "super class."
class Duck():
def __init__(self, name=None):
self.name = name
def quack(self):
print("QUACK! My name is {}.".format(self.name))
# all ducks can quack, and can say their name.
ducky = Duck("Ducky")
ducky.quack()
# >> "QUACK! My name is Ducky."
# Mallards are Ducks, too --
class Mallard(Duck):
pass
# to make Mallard inherit from Duck, we define the class this way.
# now, Mallards can quack, even though we didn't "teach" them how: they are Ducks.
ducky2 = Mallard("ducky2")
ducky2.quack()
# >> "QUACK! My name is ducky2."
# But Mallards don't quack, they honk.
class Mallard2(Duck):
def quack(self):
print("HONK! My name is {}.".format(self.name))
# This method will completely override the one defined in the parent class, Duck.
mallard = Mallard2("mallard_duck")
mallard.quack()
# >> "HONK! My name is mallard_duck."
# Some ducks quack normally, but add some more information.
class Darkwing(Duck):
def quack(self):
super(Darkwing, self).quack()
print("Let's get dangerous.")
dwd = Darkwing("DWD")
dwd.quack()
# >> "Quack! My name is dwd."
# >> "Let's get dangerous."
# This way lets us call both the method we define on the child class, and the
# original parent class method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment