简体   繁体   中英

Is it a good practice to add object instance attributes according to some condition?

I have the following python code, where I create a food object, which adds instance attributes according to the food type:

class Food:  
      def __init__(self, type):
            self.type=type
            if type=="milk":
                self.__add_milk_attributes()
            else:
                self.__add_apple_attributes()
       
      def ___add_milk_attributes():
          self.liters= 2
          self.fat_precentage=1
          # more attributes of milk

      def ___add_apple_attributes():
          self.wight= 1
          self.color="red"
          # more attributes of apple

Is it a good practice to add dynamic attributes as above? I know that Pycharm returns weak warnings that all field should be initiated in the constructor.

Edit: The user cannot accesses the internal object implementation (ie, Apple or Milk), and should only access the Food constructor to create the object. Thus, inheritance alone is not enough. Is there a way to call the Apple/Milk constructor from the Food contractor, without creating a new object?

From my point of view this kind of problems must be solved with inheritance, so you should have three different classes.

A "base class" that is Food:

class Food:  
    def __init__(self, type):
        self.type = type

Then, another class for Milk:

class Milk(Food):
    def __init__(self, type, liters, fat_precentage):
        super().__init__(type)
        self.liters = liters
        self.fat_precentage = fat_precentage

And another one for Apple:

class Apple(Food):
    def __init__(self, type, wight, color):
        super().__init__(type)
        self.wight = wight
        self.color = color

This approach allows you to have more flexible code for any future changes (for example think if you need to add another 10 foods). Then, I think it is also more readable and debuggable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM