55.2k views
5 votes
Create a Driver class to use your Farm and Animal classes and create instances of them. In the main method do the following: Create a Farm of size 10 Create 5 Animal Objects with the details specified in the table below Add the 5 Animal objects to the Farm Call the printDetails method from the Farm to print all the Farm and Animal details. variable name name birthYear weight gender a1 cow 2012 1000.5 ‘f’ a2 pig 2009 550.5 ‘m’ a3 donkey 1999 773.42 ‘m’ a4 sheep 2016 164.23 ‘f’ a5 goose 2004 10.75 ‘f’

User Yeshyyy
by
6.9k points

1 Answer

4 votes

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.

User Seeliang
by
7.4k points