An example of usage of a Driver class that uses Farm and Animal classes, creates instances of them, adds Animal objects to the Farm, and calls the printDetails method is shown below:
python
class Animal:
def __init__(self, name, species, birth_year, weight, gender):
self.name = name
self.species = species
self.birth_year = birth_year
self.weight = weight
self.gender = gender
def get_details(self):
return f"{self.name} - {self.species}, Born: {self.birth_year}, Weight: {self.weight}kg, Gender: {self.gender}"
class Farm:
def __init__(self, size):
self.size = size
self.animals = []
def add_animal(self, animal):
if len(self.animals) < self.size:
self.animals.append(animal)
return True
else:
return False
def print_details(self):
print(f"Farm Size: {self.size}")
print("Farm Animals:")
for animal in self.animals:
print(animal.get_details())
class Driver:
atstaticmethod
def main():
farm_size = 10
farm = Farm(farm_size)
a1 = Animal("cow", "Cow", 2012, 1000.5, 'f')
a2 = Animal("pig", "Pig", 2009, 550.5, 'm')
a3 = Animal("donkey", "Donkey", 1999, 773.42, 'm')
a4 = Animal("sheep", "Sheep", 2016, 164.23, 'f')
a5 = Animal("goose", "Goose", 2004, 10.75, 'f')
animals = [a1, a2, a3, a4, a5]
for animal in animals:
if farm.add_animal(animal):
print(f"{animal.name} added to the farm.")
else:
print(f"Farm is full. Unable to add {animal.name}.")
farm.print_details()
if __name__ == "__main__":
Driver.main()
What is the Driver class?
This script defines an Animal class with a constructor and a get_details method, a Farm class with methods for adding animals and printing details.
Therefore, it also has a Controller class with a main method that creates creates instances of Animal and Farm, adds animals to the farm, and prints the details.