[Edu-sig] an OO example (another zoo.py)

kirby urner kirby.urner at gmail.com
Thu Apr 15 01:43:13 CEST 2010


"""
playing with polymorphism
by Kirby Urner
Portland, Oregon
April, 2010
"""

import re
from random import choice

class Animal(object):

    def __init__(self, name):
        self.name = name
        self.stomach = []

    def eat(self, food):
        self.stomach.append(food)

    def poop(self):
        if len(self.stomach) > 0:
            return self.stomach.pop(0) # queue

    def noise(self, howmany):
        pass

    def __repr__(self):
        return "A %s named %s in location %s" %
(self.__class__.__name__, self.name, id(self))

class Mammal(Animal):

    def __init__(self, name):
        self.blood = "warm"
        super(Mammal, self).__init__(name)

class Reptile(Animal):

    def __init__(self, name):
        self.blood = "ambient"
        super(Reptile, self).__init__(name)

class Monkey(Mammal):

    def noise(self, howmuch):
        noises= ["Hoot","Screech","Jabber"]
        return "! ".join([choice(noises) for i in range(howmuch)])+"! "

class Dog(Mammal):

    def noise(self, numbarks):
        return numbarks * "Woof! "

class Snake(Reptile):

    def noise(self, howmany):
        return "Hissss.. " * howmany

def test1():
    animal1 = Dog("Spot")
    animal2 = Monkey("Red Devil")
    animal3 = Snake("Barry")
    print animal1, "goes: \n", animal1.noise(3)
    print animal2, "goes: \n", animal2.noise(4)
    print animal2, "goes: \n", animal2.noise(1)
    print animal1, "blood ", animal1.blood
    print animal2, "blood ", animal2.blood
    print animal3, "blood ", animal3.blood

if __name__== "__main__":
    test1()


More information about the Edu-sig mailing list