Created
October 25, 2017 00:37
-
-
Save bradmontgomery/9681388df46e43e852ca6ae51d6c00c1 to your computer and use it in GitHub Desktop.
Example code illustrating some simple Object-Oriented Programming concepts.
This file contains 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: | |
# This is our base class that describes an Animal. | |
sound = "..." # The default sound an animal makes. | |
def __init__(self, sound=None): | |
# This is a constructor method. It will | |
# set up an animal's sound. | |
if sound: | |
self.sound = sound | |
def say(self): | |
# Print the sound an animal makes. | |
print(self.sound) | |
class MotionMixin: | |
# This is a class that describes motion. | |
# It can be used alongside the Animal class | |
how = 'walk' | |
def move(self): | |
print("The {} {}s".format(self.__class__.__name__, self.how)) | |
class Dog(MotionMixin, Animal): | |
# The dog class inherits from both MotionMixin and | |
# Animal. This is an example of multiple inheritance. | |
sound = "bark" | |
def say(self): | |
print("The dog says, '{}'".format(self.sound)) | |
class Cat(Animal): | |
# The Cat class inherits only from Animal. | |
sound = "MEOOOOW" | |
if __name__ == "__main__": | |
# This is our "main program". Run it with: python oo_example.py | |
# Create a dog using the Dog class and call its methods. | |
dog = Dog() | |
dog.say() | |
dog.move() | |
# Create a cat using the Cat class and call its methods. | |
cat = Cat() | |
cat.say() | |
cat.move() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment