Created
October 27, 2014 03:47
-
-
Save rtoal/331c855a8092e82673dd to your computer and use it in GitHub Desktop.
An example of inheritance and polymorphism in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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