""" barnyard.py An example of objects (classes) in python, illustrating * a class variable Animal.population, one for whole class * instance variables self.name for each individual animal * the __str__ method str() output ; how the class prints * class inheritance "isa" relationship : "A Dog is a Animal" * a container class one class with instances of another within it. Jim M | cs.marlboro.edu | Oct 2016 | MIT License """ class Animal(object): """ Each animal has a characteristic sound. The total number of animals is Animal.population . """ # This is a class variable, whose full name is Animal.population. # There is only one of these, for the whole class. # (Not one per instance, # (Its full name is Animal.population.) population = 0 def __init__(self, name=''): self.name = name Animal.population += 1 self.initialize() def initialize(self): """ Change this in the inherited classes """ self.what = 'Animal' self.sound = '?' def __str__(self): if self.name: return '{}(name="{}")'.format(self.what, self.name) else: return '{}()'.format(self.what) def speak(self): """ Return a string describing what this animal says. """ result = ' {}'.format(self.what) if self.name: result = result + ' named "{}"'.format(self.name) result = result + ' says {}'.format(self.sound) return result class Dog(Animal): """ A dog says 'woof' >>> spot = Dog(name='Spot') >>> spot.speak() ' Dog named "Spot" says woof' >>> print spot Dog(name="Spot") """ def initialize(self): self.what = 'Dog' self.sound = 'woof' class Cat(Animal): """ A cat says 'meow' """ def initialize(self): self.what = 'Cat' self.sound = 'meow' class Zoo(object): """ A bunch of animals """ def __init__(self): self.animals = [] def add(self, animal): self.animals.append(animal) def print_chorus(self): """ Let the animals speak """ for animal in self.animals: print animal.speak() def main(): barnyard = Zoo() for creature in (Dog, Cat, Dog, Dog): # creature is a class ... barnyard.add( creature() ) # ... and this creates one! barnyard.add( Cat(name='Mr. Mistoffelees') ) print 'The barnyard has {} animals :'.format(Animal.population) barnyard.print_chorus() if __name__ == '__main__': import doctest doctest.testmod() main()