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

Python类方法调用报错:已传全部参数仍提示缺少必需位置参数

问题分析与解决方案

错误原因梳理

  1. 实例创建错误:原代码中dishwasher = Dish_Washer仅将类对象赋值给变量,未创建类的实例。用类直接调用实例方法时,Python会要求传入self参数(即实例本身),导致参数数量不匹配,触发missing 1 required positional argument报错。正确写法需添加括号创建实例:dishwasher = Dish_Washer()。
  2. 方法名非法:Python的标识符(方法、变量名)不允许包含空格,原代码中wash dishes不符合语法规范,需改为wash_dishes。
  3. 冗余代码:start_cycle方法内的is_on = is_on和door_closed = door_closed属于无效赋值,直接使用传入的参数即可。

修正后的完整代码

class Dish_Washer:
    def heat_water(self):
        print("Water is heating")

    def wash_dishes(self):  # 修正方法名,移除空格
        print("Dishes are washing")

    def open_door_malfunction(self):
        print("Door is open")
    
    def start_cycle(self, is_on, door_closed):
        if not door_closed:
            self.open_door_malfunction()
        elif is_on and door_closed:
            self.heat_water()
            self.wash_dishes()

# 创建类的实例
dishwasher = Dish_Washer()
dishwasher.start_cycle(True, True)

运行结果

执行修正后的代码,终端将输出预期内容:

Water is heating
Dishes are washing

内容的提问来源于stack exchange,提问作者John Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 06:07:28