Skip to content

Instantly share code, notes, and snippets.

@yoavram
Created November 27, 2011 15:12
Show Gist options
  • Save yoavram/1397677 to your computer and use it in GitHub Desktop.
Save yoavram/1397677 to your computer and use it in GitHub Desktop.
An OOP example of Old McDonanld Had a Farm
class Farm:
def __init__(self):
self.animals = []
def add(self, animal):
self.animals.append(animal)
def __str__(self):
s = ''
for animal in self.animals:
s += 'Old MacDonald had a farm, EE-I-EE-I-O,\n'
s += 'And on that farm he had a ' + animal.name + ', EE-I-EE-I-O,\n'
s += 'With a ' + animal.noise * 2 + ' here and a ' + animal.noise * 2 +' there\n'
s += 'Here a ' + animal.noise + ', there a ' + animal.noise + ', everywhere a '+ animal.noise * 2 + '\n'
s += 'Old MacDonald had a farm, EE-I-EE-I-O.\n'
return s
class Animal:
def __init__(self, name, noise):
self.name = name
self.noise = noise
farm = Farm()
farm.add(Animal('cow', 'moo'))
print farm
farm.add(Animal('duck', 'kwak'))
farm.add(Animal('dog', 'woof'))
farm.add(Animal('cat', 'miaoo'))
print farm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment