Skip to content

Instantly share code, notes, and snippets.

@rtoal
Created October 27, 2014 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtoal/331c855a8092e82673dd to your computer and use it in GitHub Desktop.
Save rtoal/331c855a8092e82673dd to your computer and use it in GitHub Desktop.
An example of inheritance and polymorphism in Python
"""A module with talking animals."""
class Animal(object):
def __init__(self, name):
self.name = name
def speak(self):
print self.name, 'says', self.sound()
class Cow(Animal):
def __init__(self, name):
super(Cow, self).__init__(name)
def sound(self):
return 'moo'
class Horse(Animal):
def __init__(self, name):
super(Horse, self).__init__(name)
def sound(self):
return 'neigh'
class Sheep(Animal):
def __init__(self, name):
super(Sheep, self).__init__(name)
def sound(self):
return 'baaaaa'
if __name__ == '__main__':
s = Horse('CJ')
s.speak()
c = Cow('Bessie')
c.speak()
Sheep('Little Lamb').speak()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment