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' 值,我不明白這一點。
也許有人可以發現錯誤?
uj5u.com熱心網友回復:
您有初始化類所有的引數:item_name,amount_fat,amount_carbs,amount_protein和num_servings。
# here, you have to provide the arguments
food_item1 = FoodItem()
...
# and here, you are missing the 'num_servings' argument
food_item2 = FoodItem(item_name, amount_fat, amount_carbs, amount_protein)
以防萬一,您可以為引數提供默認值,如下所示:
# here, the argument will default to '0' if you do not provide a value.
class Example:
def __init__(self, argument=0):
self.argument = argument
example = Example()
print(example.argument)
>>> 0
uj5u.com熱心網友回復:
您的代碼沒有說明要匹配什么,例如 self.amount_fat 與您正在談論的引數。你應該寫: self.amount_fat = amount_fat
然后announce 是self.amount_fat 是,否則你的程式將不知道從哪里讀取。
def __init__(self, item_name, amount_fat, amount_carbs, amount_protein, num_servings):
self.item_name = item_name
self.amount_fat = amount_fat
self.amount_carbs = amount_carbs
self.amount_protein = amount_protein
self.num_servings = num_servings
然后,您可以添加最初編碼的內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/367190.html
上一篇:如何從前端(Reactjs)到后端(Nodejs,MySQL)獲取指定用戶的資料
下一篇:呼叫CompleteMultipartUpload操作時發生錯誤(EntityTooSmall):您建議的上傳小于允許的最小大小
