【问题标题】:__init__ within class supposedly missing arguments?类中的 __init__ 应该缺少参数?
【发布时间】: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__ 的参数没有被使用,而是将变量初始化为硬编码值。

标签: python class init


【解决方案1】:

您的代码没有说明要匹配什么,例如 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

然后您可以添加您最初编码的内容。

【讨论】:

    【解决方案2】:

    您必须使用 ALL 参数初始化您的类:item_nameamount_fatamount_carbsamount_proteinnum_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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多