# AnimalsSolutions.py Copyright (c) Kari Laitinen # http://www.naturalprogramming.com # 2009-01-06 File created. # 2022-12-28 Converted to Python 3. # Solutions to the exercises with Animals.py class Animal : def __init__( self, first_parameter = "default animal", second_parameter = "nameless" ) : if isinstance( first_parameter, str ) : # The given parameter is a string. We suppose that a new # Animal object with the given species name is being constructed. self.species_name = first_parameter self.animal_name = second_parameter self.stomach_contents = "" elif isinstance( first_parameter, Animal ) : # A reference to an Animal object was given as an actual parameter. # The new Animal object will be a copy of the given Animal object. self.species_name = first_parameter.species_name self.animal_name = first_parameter.animal_name self.stomach_contents = first_parameter.stomach_contents else : print( "\n Unacceptable object was given to Animal constructor." ) def feed( self, food_for_this_animal ) : if isinstance( food_for_this_animal, str ) : self.stomach_contents = \ self.stomach_contents + food_for_this_animal + ", " elif isinstance( food_for_this_animal, Animal ) : self.stomach_contents = \ self.stomach_contents + food_for_this_animal.animal_name + ", " food_for_this_animal.animal_name = "Eaten animal" def make_speak( self ) : print( "\n Hello, I am a " + self.species_name + " named " \ + self.animal_name, end="" ) if ( len( self.stomach_contents ) == 0 ) : print( "\n My stomach is empty." ) else : print( "\n I have eaten: " + self.stomach_contents + "\n" ) # The main program begins here. cat_object = Animal( "cat" ) dog_object = Animal( "vegetarian dog" ) cat_object.feed( "fish" ) cat_object.feed( "chicken" ) dog_object.feed( "salad" ) dog_object.feed( "potatoes" ) another_cat = Animal( cat_object ) another_cat.feed( "milk" ) cat_object.make_speak() dog_object.make_speak() another_cat.make_speak() default_animal = Animal() default_animal.make_speak() tiger_object = Animal( "tiger", "Richard" ) cow_object = Animal( "cow", "Bertha" ) tiger_object.feed( cow_object ) tiger_object.make_speak() cow_object.make_speak()