Greetings,
I started learning python about 6 months ago. I came from various other languages. So, the things that cause me the most difficulty are Abstraction, protected, private methods and properties and decorators.
1. In my example below,
2. How would I ensure that the 'name' property was set before it is called?
3. What do the combined decorators below do exactly?
Matt
I started learning python about 6 months ago. I came from various other languages. So, the things that cause me the most difficulty are Abstraction, protected, private methods and properties and decorators.
1. In my example below,
from abc import ABC, abstractmethodis the module I am using the standard for creating abstract classes?
2. How would I ensure that the 'name' property was set before it is called?
3. What do the combined decorators below do exactly?
@property @abstractmethod def diet(self): pass
# Create Abstract class from abc import ABC, abstractmethod # Abstract Class # Use protected variable self._name, self._food class Animal(ABC): @property def food_eaten(self): return self._food @food_eaten.setter def food_eaten(self, food): if food in self.diet: self._food = food else: raise ValueError(f"You can't feed this animal with {food}.") @property @abstractmethod def diet(self): pass @abstractmethod def feed(self, time): pass @property def name(self): return self._name @name.setter def name(self, name): self._name = name class Dog(Animal): @property def diet(self): return ['Dog Food', 'Steak', 'Pork', 'Chicken'] def feed(self, time): print(f"Feeding {self._name} with {self._food} meat! At {time}") class Cat(Animal): @property def diet(self): return ['Cat Food', 'Fish', 'Soup'] def feed(self, time): print(f"Feeding {self._name} with {self._food} meat! At {time}") nico = Dog() nico.name = 'Nico' nico.food_eaten = 'Dog Food' print(nico.food_eaten) print(nico.name) nico.feed("10:10 AM")
Output:Dog Food
Nico
Feeding Nico with Dog Food meat! At 10:10 AM
Thank you in advance,Matt