[英]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:我有以下 python 代码,其中我创建了一个食物 object,它根据食物类型添加实例属性:
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.
我知道 Pycharm 返回弱警告,所有字段都应在构造函数中启动。
Edit: The user cannot accesses the internal object implementation (ie, Apple or Milk), and should only access the Food constructor to create the object.编辑:用户无法访问内部 object 实现(即 Apple 或 Milk),并且只能访问 Food 构造函数来创建 object。 Thus, inheritance alone is not enough.
因此,仅 inheritance 是不够的。 Is there a way to call the Apple/Milk constructor from the Food contractor, without creating a new object?
有没有办法从食品承包商调用 Apple/Milk 构造函数,而不创建新的 object?
From my point of view this kind of problems must be solved with inheritance, so you should have three different classes.从我的角度来看,这种问题必须用 inheritance 来解决,所以你应该有三个不同的类。
A "base class" that is Food:作为 Food 的“基类”:
class Food:
def __init__(self, type):
self.type = type
Then, another class for Milk:然后,另一个用于牛奶的 class:
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).这种方法使您可以为将来的任何更改提供更灵活的代码(例如,考虑是否需要再添加 10 种食物)。 Then, I think it is also more readable and debuggable
然后,我认为它也更具可读性和可调试性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.