Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Abstraction Module (ABC)
#1
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,
from abc import ABC, abstractmethod
is 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
Reply


Messages In This Thread
Abstraction Module (ABC) - by muzikman - Aug-03-2021, 01:08 PM
RE: Abstraction Module (ABC) - by deanhystad - Aug-03-2021, 02:42 PM
RE: Abstraction Module (ABC) - by muzikman - Aug-03-2021, 04:05 PM
RE: Abstraction Module (ABC) - by muzikman - Aug-03-2021, 04:21 PM
RE: Abstraction Module (ABC) - by deanhystad - Aug-03-2021, 04:48 PM
RE: Abstraction Module (ABC) - by muzikman - Aug-03-2021, 06:00 PM
RE: Abstraction Module (ABC) - by muzikman - Aug-03-2021, 04:58 PM
RE: Abstraction Module (ABC) - by deanhystad - Aug-03-2021, 05:58 PM
RE: Abstraction Module (ABC) - by muzikman - Aug-03-2021, 06:03 PM
RE: Abstraction Module (ABC) - by deanhystad - Aug-03-2021, 10:00 PM
RE: Abstraction Module (ABC) - by muzikman - Aug-06-2021, 06:12 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020