def setUp(self): """ Create animals for testing purposes. TODO - take the animals from a database instead """ self.sharo = Dog('Sharo', 'unbred', 5, "male") self.lucy = Dog('Lucy', 'collie', 3, "Female") self.daisy = Dog('Daisy', 'labrador', 2, "fem") self.rocco = Dog('Rocco', 'German Shepherd', 1, "M") self.duke = Dog('Duke', 'Doberman', 4, "Male") self.mike = Dog('Mike', 'Doberman', 4, "Male") self.max_ = Dog('Max', 'greyhound', 7, "M") self.maya = Cat('Maya', 'Sphynx', 5, "F") self.ruh = Cat('Ruh', 'unbred', 3, "male") self.tiger = Cat('Tiger', 'SAVANNAH', 4, "M") # Create a non-animal object self.non_animal_object = (5, "F") # Create a Pool with dogs for adoption self.dog_pool = [ self.sharo, self.lucy, self.daisy, self.rocco, self.duke, self.mike, self.max_ ] # Create a Pool with cats for adoption self.cat_pool = [self.maya, self.ruh, self.tiger]
def create_animal(name): if name == 'dog': return Dog() elif name == 'cat': return Cat() else: raise Exception("error input")
Programa creado para mostrar ejemplos prácticos para contrastar contra la programamación procedural ''' __author__ = "Inove Coding School" __email__ = "*****@*****.**" __version__ = "1.1" from animal import Dog, Cat, Cow import person as p if __name__ == '__main__': animal_1 = Dog('Sirius', 8) animal_2 = Cat('Minerva', 1) print('¿Cuanto duerme el perro por la noche?', animal_1.sleep()) print('¿Cuanto duerme el gato por la noche?', animal_2.sleep()) persona = p.Person('Max') print('{} adoptó 2 animales, un perro y un gato'.format(persona.name)) persona.adopt(animal_1) persona.adopt(animal_2) print('¿Cómo saludan los animales de', persona.name, '?') for animal in persona.animales: animal.speak()
from animal import Dog, Cat Luna = Dog(name='Luna', age=3) Loly = Cat(name='Loly', age=5) print(Luna.speak()) print(Loly.speak())
def main(): zoo = [] #Cats Carmen = Cat("Carmen") zoo.append(Carmen) Chloe = Cat("Chloe") zoo.append(Chloe) Caidy = Cat("Caidy") zoo.append(Caidy) #Lions Leeroy = Lion("Leeroy") Leeroy.setAnimalEat(AnimalEatMeat()) zoo.append(Leeroy) Leon = Lion("Leon") Leon.setAnimalEat(AnimalEatMeat()) zoo.append(Leon) #Tigers Tony = Tiger("Tony") Tony.setAnimalEat(AnimalEatMeat()) zoo.append(Tony) Tom = Tiger("Tom") Tom.setAnimalEat(AnimalEatMeat()) zoo.append(Tom) Timmy = Tiger("Timmy") Timmy.setAnimalEat(AnimalEatMeat()) zoo.append(Timmy) #Elephants Edith = Elephant("Edith") Edith.setAnimalEat(AnimalEatVegetarian()) zoo.append(Edith) Erin = Elephant("Erin") Erin.setAnimalEat(AnimalEatVegetarian()) zoo.append(Erin) #Rhinos Ryan = Rhino("Ryan") Ryan.setAnimalEat(AnimalEatVegetarian()) zoo.append(Ryan) Robert = Rhino("Robert") Robert.setAnimalEat(AnimalEatVegetarian()) zoo.append(Robert) Ronan = Rhino("Ronan") Ronan.setAnimalEat(AnimalEatVegetarian()) zoo.append(Ronan) #Hippos Harper = Hippo("Harper") Harper.setAnimalEat(AnimalEatVegetarian()) zoo.append(Harper) Hector = Hippo("Hector") Hector.setAnimalEat(AnimalEatVegetarian()) zoo.append(Hector) #Dogs Douglas = Dog("Douglas") Douglas.setAnimalEat(AnimalEatMeat()) zoo.append(Douglas) Damian = Dog("Damian") Damian.setAnimalEat(AnimalEatMeat()) zoo.append(Damian) Dominic = Dog("Dominic") Dominic.setAnimalEat(AnimalEatMeat()) zoo.append(Dominic) Daisy = Dog("Daisy") Daisy.setAnimalEat(AnimalEatMeat()) zoo.append(Daisy) #Wolves Wilson = Wolf("Wilson") Wilson.setAnimalEat(AnimalEatMeat()) zoo.append(Wilson) Wendy = Wolf("Wendy") Wendy.setAnimalEat(AnimalEatMeat()) zoo.append(Wendy) #PROOF OF DYNAMIC BEHAIVOR AT RUN TIME #(All other eat behaivor set at object instatiation above) Carmen.setAnimalEat(AnimalEatPreMixedFood()) Caidy.setAnimalEat(AnimalEatPreMixedFood()) Chloe.setAnimalEat(AnimalEatPreMixedFood()) Kanye = Zookeeper(zoo) #Subject Kim = ZooAnnouncer(Kanye) #Observer Kanye.registerObserver(Kim) Kanye.beAZookeeper() del Kim del Kanye for animal in zoo: del animal
from animal import Animal, Cat class Zoo(object): """ class Zoo """ def __init__(self, name): self.name = name def add_animal(self, animal: Animal): setattr(self, animal.__class__.__name__, animal) if __name__ == '__main__': # 实例化动物园 z = Zoo('时间动物园') # 实例化一只猫,属性包括名字、类型、体型、性格 cat1 = Cat('大花猫 1', 'predacity', 'small', 'tender', True) # 增加一只猫到动物园 z.add_animal(cat1) # 动物园是否有猫这种动物 have_cat = hasattr(z, 'Cat') print(have_cat) print(z.Cat)
from animal import Dog, Cat kiki = Dog (name='kiki',age=3) mimi= Cat(name='mimi',age=5) print(kiki.speak()) print(mimi.speak())
from animal import Cat, Dog fufu = Dog(name='fufu', age=3) bailey = Cat(name='bailey', age=7) print(fufu.speak()) print(bailey.speak()) # Dog and Cat have inherited 'speak' from Class Animal
from animal import Dog, Cat fufu = Dog(name='fufu', age=3) baxter = Cat(name='baxter', age=5) print(fufu.speak()) print(baxter.speak())
class TestAdoptionService(unittest.TestCase): def setUp(self): """ Create animals for testing purposes. TODO - take the animals from a database instead """ self.sharo = Dog('Sharo', 'unbred', 5, "male") self.lucy = Dog('Lucy', 'collie', 3, "Female") self.daisy = Dog('Daisy', 'labrador', 2, "fem") self.rocco = Dog('Rocco', 'German Shepherd', 1, "M") self.duke = Dog('Duke', 'Doberman', 4, "Male") self.mike = Dog('Mike', 'Doberman', 4, "Male") self.max_ = Dog('Max', 'greyhound', 7, "M") self.maya = Cat('Maya', 'Sphynx', 5, "F") self.ruh = Cat('Ruh', 'unbred', 3, "male") self.tiger = Cat('Tiger', 'SAVANNAH', 4, "M") # Create a non-animal object self.non_animal_object = (5, "F") # Create a Pool with dogs for adoption self.dog_pool = [ self.sharo, self.lucy, self.daisy, self.rocco, self.duke, self.mike, self.max_ ] # Create a Pool with cats for adoption self.cat_pool = [self.maya, self.ruh, self.tiger] def test_class_instances(self): """Test the class of the set-up animal instances """ self.assertIsInstance(self.sharo, Dog) self.assertNotIsInstance(self.lucy, Cat) self.assertIsInstance(self.maya, Cat) self.assertNotIsInstance(self.ruh, Dog) self.assertIsInstance(self.tiger, Animal) self.assertIsNot(self.non_animal_object, Animal) def test_animal_age(self): """ Test the age of the animal instances """ self.assertEqual(self.sharo.get_age(), 5) self.assertNotEqual(self.daisy.get_age(), 512) def test_animal_breed(self): """ Test the breed of the animal instances """ self.assertEqual(self.lucy.get_breed(), 'collie') # Akita breed is not in the list of available breeds: with self.assertRaises(AssertionError): Dog('Mollie', 'Akita', 6, 'Male') def test_animal_gender(self): """ Test the gender of the animal instances """ self.assertEqual(self.rocco.get_gender(), 'M') self.assertEqual( Dog('Bobby', 'chow chow', 6, 'Unknown_gender').get_gender(), 'Other') def test_eat_method(self): """ Test the eat method of the animal instances """ self.assertEqual("I like to eat bones.", self.sharo.eat("bones")) self.assertEqual("I like to eat fish.", self.ruh.eat("fish")) self.assertEqual("I like to eat chicken soup.", self.tiger.eat("chicken soup")) def test_adoption_methods(self): """ Test the adoption methods of the Adoption Center Factory """ dog_adoption_center = AdoptionCenterFactory(self.dog_pool) cat_adoption_center = AdoptionCenterFactory(self.cat_pool) # Adopt a dog that exists in the Pool message, result = dog_adoption_center.adopt_animal("doberman", 4, "M") self.assertIsInstance(result, Dog) # Assert that the adopted dog has been removed from the Dog pool: self.assertNotIn(result, self.dog_pool) # Assert that the user received a proper message and only Duke is returned: self.assertEqual( "You adopted a Doberman named Duke that is 4 years old and a boy.", message) # Try to adopt a dog that doesn't exist in the Pool message, result_list = dog_adoption_center.adopt_animal( "labrador", 3, "F") # Assert that the proper message has been returned self.assertIn( "Sorry, we don't have this pet in our shop!" " Would you consider adopting one of these cuties instead: ", message) self.assertIn("Daisy", str(result_list[0])) # Daisy has same breed + gender self.assertIn("Lucy", str(result_list[1])) # Lucy has same gender + age # Adopt a random cat from the Pool message, result = cat_adoption_center.get_lucky() self.assertIsInstance(result, Cat) # Assert that the lucky cat has been removed from the Cat pool self.assertNotIn(result, self.cat_pool) # Assert that the user received a proper message self.assertEqual("You adopted a {}.".format(str(result)), message)
from animal import Dog, Cat fufu = Dog(name='fufu', age=3) baxter = Cat(name="Baxter", age=5) print(fufu.speak()) print(baxter.speak())
def create_animal(self): return Cat()
class AnimalFactory(object): def create_animal(self): raise NotImplementedError("can not use create_animal on AnimalFactory") class DogFactory(AnimalFactory): def create_animal(self): return Dog() class CatFactory(AnimalFactory): def create_animal(self): return Cat() if __name__ == '__main__': animal_factory = DogFactory() dog = animal_factory.create_animal() dog.eat() animal_factory = CatFactory() cat = animal_factory.create_animal() cat.eat() # 如此一来,增加产品时不用改原有代码,只需要增加产品子类和工厂子类即可(加个FishFactory,Fish) # 实际上,对于Java等强类型语言工厂方法可以使用,python是弱类型的,感觉没必要用 # 对于python实际上直接用下面方式就行 dog = Dog() cat = Cat()
elif animal.name == 'snake': print("Hsss!") else: print("----") [make_sound(a) for a in [dog, cat, lion, snake]] print("-" * 10) # The better way, as we implemented in animial.py, is to create separate classes for these # new animals to implement an Animal.make_sound function. from animal import Dog, Cat, Lion, Snake dog = Dog('dog') cat = Cat('cat') lion = Lion('lion') snake = Snake('snake') [a.make_sound() for a in [dog, cat, lion, snake]] # Look how easy it is to add a duck! class Duck(Animal): def __init__(self, name): super(Duck, self).__init__(name) def make_sound(self): print("Quack!")
from animal import Animal, Dog, Cat if __name__ == "__main__": animals = (Animal(), Dog(), Cat()) for animal in animals: animal.speak() for animal in animals: animal.sleep()