You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类实例化时提示__init__缺少必填参数的问题排查求助

问题原因

  • 构造方法参数默认值设置位置错误
    你在__init__方法内部给属性赋值的固定值,不属于参数默认值。Python要求实例化类时必须传入所有未在参数列表中声明默认值的参数,你当前的__init__参数列表共有5个无默认值的参数,调用FoodItem()不传参自然会触发参数缺失报错。
  • 属性名不统一
    你在__init__中定义的属性名为item_name、amount_fat、amount_carbs、amount_protein,但在get_calories、print_info方法中调用的是self.name、self.fat、self.carbs、self.protein,名称完全不匹配,参数问题修复后仍会触发属性不存在的报错。
  • 实例化参数数量不匹配
    原__init__要求传入5个参数,你实例化food_item2时仅传入4个,参数问题修复后此处也会触发报错。

修正后的代码

class FoodItem:
    # 把默认值写在参数列表中,同时将传入的参数赋值给属性
    def __init__(self, item_name="None", amount_fat=0.0, amount_carbs=0.0, amount_protein=0.0, num_servings=0.0):
        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
       
    def get_calories(self, num_servings):
        # 统一属性名
        calories = ((self.amount_fat * 9) + (self.amount_carbs * 4) + (self.amount_protein * 4)) * num_servings
        return calories
       
    def print_info(self):
        # 统一属性名
        print('Nutritional information per serving of {}:'.format(self.item_name))
        print('   Fat: {:.2f} g'.format(self.amount_fat))
        print('   Carbohydrates: {:.2f} g'.format(self.amount_carbs))
        print('   Protein: {:.2f} g'.format(self.amount_protein))

if __name__ == "__main__":
    # 无参调用走参数默认值
    food_item1 = FoodItem()
   
    item_name = input()
    amount_fat = float(input())
    amount_carbs = float(input())
    amount_protein = float(input())
   
    # 传入4个参数,剩下的num_servings走默认值即可
    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)))

内容的提问来源于stack exchange,提问作者Jacob Ivanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:54:02