task:
Create a Pets class that holds instances of dogs; this class is completely separate from the Dog class. In other words, the Dog class does not inherit from the Pets class. Then assign three dog instances to an instance of the Pets class.
solution:
1. why in class Pets it is necessary to open an empty list
3. in
Create a Pets class that holds instances of dogs; this class is completely separate from the Dog class. In other words, the Dog class does not inherit from the Pets class. Then assign three dog instances to an instance of the Pets class.
solution:
# Parent class class Dog: # Class attribute species = 'mammal' # Initializer / Instance attributes def __init__(self, name, age): self.name = name self.age = age # instance method def description(self): return "{} is {} years old".format(self.name, self.age) # instance method def speak(self, sound): return "{} says {}".format(self.name, sound) # Child class (inherits from Dog class) class RussellTerrier(Dog): def run(self, speed): return "{} runs {}".format(self.name, speed) # Child class (inherits from Dog class) class Bulldog(Dog): def run(self, speed): return "{} runs {}".format(self.name, speed) # Parent class class Pets: dogs = [] def __init__(self, dogs): self.dogs = dogs my_dogs = [ Bulldog("Tom", 6), RussellTerrier("Fletcher", 7), Dog("Larry", 9) ] # Instantiate the Pets class my_pets = Pets(my_dogs) print(f'I have {len(my_pets.dogs)} dogs.') for dog in my_pets.dogs: print(f'{dog.name} is {dog.age}') print(f'And they\'re all {dog.species}s, of course.')I have several questions regarding this solution:
1. why in class Pets it is necessary to open an empty list
dogs = []2. this line confuses me:
print(f'I have {len(my_pets.dogs)} dogs.')why my_pets.dogs? I don't see a connection. dogs is attribute of the class Pet. Does dogs represents names in my_dogs list methods?
3. in
for dog in my_pets.dogs:what is dog?