Have you ever dreamt about coding classes like a pro? No? You had “normal” dreams? Anyway, in the video below, I am solving 3 exercises with a lot of debugging and some basic tests. Exercises are from the book Python Workout and I am using Jupyter Notebook as IDE.
The code in GitHub is here. In general, these are the exercises:
Exercise 43:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Exercise 43 class Animal(): def __init__(self, color, number_of_legs): self.species = self.__class__.__name__.lower() self.color = color self.number_of_legs = number_of_legs def __repr__(self): return f'{self.color} {self.species}, {self.number_of_legs} legs' class Sheep(Animal): def __init__(sef, color): super().__init__(color, 4) class Wolf(Animal): def __init__(sef, color): super().__init__(color, 4) class Parrot(Animal): def __init__(sef, color): super().__init__(color, 2) class Snake(Animal): def __init__(sef, color): super().__init__(color, 0) |
The interesting “thing” here is the inheritance of class Animal towards class Wolf. Additionally, this one – self.__class__.__name__.lower() saves some lines in the “Big Picture”. Using the __init__ method of Animal through the children’s classes, is also a good example.
Exercise 44:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Cage(): def __init__(self, id_num): self.id_number = id_num self.animals = [] def add_animals(self, *animals): for animal in animals: self.animals.append(animal) def __repr__(self): text = f'{self.__class__.__name__} {self.id_number}: ' text += '; '.join(str(animal) for animal in self.animals) return text |
This is a rather easy one (although I have debugged it for quite a lot of time in the video). “Composition” is the key word for this exercise – having an object, that contains other objects can be interesting and of use.
Exercise 45:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Zoo(): def __init__(self): self.cages = [] def add_cages(self, *cages): for cage in cages: self.cages.append(cage) def animals_by_color(self, filtered_color): return [animal for cage in self.cages for animal in cage.animals if animal.color == filtered_color] def animals_by_legs(self, filter_number_of_legs): return [animal for cage in self.cages for animal in cage.animals if animal.number_of_legs == filter_number_of_legs] def number_of_legs(self): return sum(animal.number_of_legs for cage in self.cages for animal in cage.animals ) def __repr__(self): return f'\n'.join(str(cage) for cage in self.cages) |
This one is the last exercise, that is actually carried out. The functions for filtering objects, by their attributes and the sum of another attribute is actually an interesting one. Talking about animals_by_legs() and number_of_legs() .
Thanks!