【发布时间】:2022-01-04 22:40:22
【问题描述】:
class FoodItem:
def __init__(self, item_name, amount_fat, amount_carbs, amount_protein, num_servings):
self.item_name = "None"
self.amount_fat = 0.0
self.amount_carbs = 0.0
self.amount_protein = 0.0
self.num_servings = 0.0
def get_calories(self, num_servings):
# Calorie formula
calories = ((self.fat * 9) + (self.carbs * 4) + (self.protein * 4)) * num_servings;
return calories
def print_info(self):
print('Nutritional information per serving of {}:'.format(self.name))
print(' Fat: {:.2f} g'.format(self.fat))
print(' Carbohydrates: {:.2f} g'.format(self.carbs))
print(' Protein: {:.2f} g'.format(self.protein))
if __name__ == "__main__":
food_item1 = FoodItem()
item_name = input()
amount_fat = float(input())
amount_carbs = float(input())
amount_protein = float(input())
food_item2 = FoodItem(item_name, amount_fat, amount_carbs, amount_protein)
num_servings = float(input())
food_item1.print_info()
print('Number of calories for {:.2f} serving(s): {:.2f}'.format(num_servings,
food_item1.get_calories(num_servings)))
print()
food_item2.print_info()
print('Number of calories for {:.2f} serving(s): {:.2f}'.format(num_servings,
food_item2.get_calories(num_servings)))
导致错误:
Traceback (most recent call last):
File "main.py", line 22, in <module>
food_item1 = FoodItem()
TypeError: __init__() missing 5 required positional arguments: 'item_name', 'amount_fat', 'amount_carbs', 'amount_protein', and 'num_servings'
我没有发现明显的错误,但我是初始化类的新手。该错误似乎表明我在原始 init 中缺少参数,但考虑到它们已初始化为 0/'none' 值,我不明白这一点。
也许有人能发现错误?
【问题讨论】:
-
food_item1 = FoodItem()。您需要像第二次一样在此处传递参数。 -
如果您想将函数更改为具有默认参数,您正在初始化类成员而不是函数参数。例如
__init__(self, item_name=0, amount_fat=0... -
错误完全清楚,
FoodItem()提供了 0 个参数,但您写了__init__需要 5 个位置参数,由错误枚举。您不完全了解什么?你为什么期望food_item1 = FoodItem()工作? -
注意,
__init__的参数没有被使用,而是将变量初始化为硬编码值。