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 (i.e., 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:
Then, another class for Milk:
And another one for Apple:
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