Created
January 30, 2015 01:42
-
-
Save kellishouts/ea33654f5df5a29d802b to your computer and use it in GitHub Desktop.
Python OOP Example
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
// oop.py | |
# class definition (blueprint) | |
class Animal: | |
# class constructor method | |
def __init__(self, name): | |
# instance properties | |
self.name = name | |
self.last_ate = None | |
print "created new animal named", name | |
def eat(self, food ): | |
self.last_ate = food | |
print self.name, "noms on", self.last_ate | |
def poop(self): | |
print self.name, "poops!!!" | |
# class definition, inherits from Animal | |
class Dog(Animal): | |
# class constructor method | |
def __init__(self): | |
# property | |
self.breed = None | |
# super call, calls the super constructor | |
Animal.__init__(self, "unnamed dog") | |
# Cat extends Animal | |
class Cat(Animal): | |
def __init__(self, name, color): | |
self.color = color | |
Animal.__init__(self, name) | |
bill = Cat("Bill the Cat", "orange and white") | |
print bill.__dict__ | |
walter = Dog() | |
walter.name = "Walter" | |
walter.breed = "Pug" | |
walter.eat("pizza") | |
walter.poop() | |
print walter.__dict__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment