Created
March 13, 2020 11:11
-
-
Save dfbarrero/0b401926b92a5e36ad08a3eae5fbd16c to your computer and use it in GitHub Desktop.
Example of 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
| class Animal: | |
| def __init__(self): | |
| self.name = "Unknown" | |
| self.age = 10 | |
| def describe(self): | |
| print("Name: ", self.name) | |
| print("Age: ", self.age) | |
| def attack(self): | |
| pass | |
| class Dog(Animal): | |
| def attack(self): | |
| print(self.name + " has bitten") | |
| class Cat(Animal): | |
| def attack(self): | |
| print(self.name + " has scratched") | |
| if __name__ == '__main__': | |
| snoopy = Dog() | |
| snoopy.name = "Snoopy" | |
| garfield = Cat() | |
| garfield.name = "Garfield" | |
| for animal in (snoopy, garfield): | |
| animal.attack() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment