# zoo.py # # This example of class inheritence is inspired by perl's "perlboot", # the "beginner's object oriented tutorial" by Randall Schwartz # which can be seen at http://perldoc.perl.org/perlboot.html . # # First, here's what it does : # # $ python zoo.py # The dog says bow-wow. # The sheep says baaaa. # The cat says meow. # The dog says bow-wow. # The cat says meow. # The sheep says baaaa. # # Now, look at the classes, methods, and functions, # and see how it all fits together. # # In particular: # # Which classes are superclasses (or 'parent' class) ? # Which are subclasses (or 'child' class) ? # Which are contained as data within other classes? # # What is the syntax for defining a subclass? # # What is the syntax for calling a superclass from within a subclass method? # # What is that "factory" function all about? Is it in a class? class Animal: """A generic Old-MacDonald-ish animal.""" def __init__(self, name="animal"): """Initialize the animal with its name.""" self.name = name def sound(self): """Return as a string the animal's sound.""" return "hmmm" def speak(self): """Return a string like 'The AnimalName says ItsSound.'.""" return "The %s says %s." % (self.name, self.sound()) class Cat(Animal): def __init__(self): Animal.__init__(self, 'cat') def sound(self): return "meow" class Dog(Animal): def __init__(self): Animal.__init__(self, 'dog') def sound(self): return "bow-wow" class Sheep(Animal): def __init__(self): Animal.__init__(self, 'sheep') def sound(self): return "baaaa" class Farm: """A collection of animals.""" def __init__(self): self.animals = [] def add(self, animal, count=1): """Add an animal to the farm.""" for i in range(count): self.animals.append(animal) def chorus(self): """Return string of animal speech.""" speech = "" for animal in self.animals: speech += animal.speak() + "\n" return speech def animal_factory(which): """Given a string like 'cat', return the corresponding animal.""" if which == 'cat': return Cat() elif which == 'dog': return Dog() elif which == 'sheep': return Sheep() def macdonald(): """Create a farm with some animals, and print their chorus.""" names = ['dog', 'sheep', 'cat', 'dog', 'cat', 'sheep'] farm = Farm() for which in names: farm.add(animal_factory(which)) print farm.chorus() macdonald()