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

Python类方法报错:传入1个位置参数但函数定义为0个

问题原因与解决办法

核心问题

你遇到的错误是因为Python的类实例方法必须在定义时声明第一个参数(通常命名为self)。当你通过实例对象调用方法时,Python会自动把该实例作为第一个位置参数传入方法中,而你定义的coordinateChecker()没有接收这个参数,所以触发了"传入1个位置参数但方法只接受0个"的错误。

修复步骤

直接修改CoordinateManager类中的coordinateChecker方法定义,添加self作为第一个参数:

class CoordinateManager:
    def __init__(self):
        self = self  # 这行无实际作用,可删除
    def coordinateChecker(self):  # 添加self参数
        global coordinates, direction, coordLimits
        DTCC = {
            "left" : [-1, 0],
            "right" : [1, 0],
            "forwards" : [0, 1],
            "backwards" : [0, -1]
        }
        coordinateChange = DTCC.get(direction)
        if not(coordLimits[0] >= (coordinates[0] + coordinateChange[0]) >= 0 and coordLimits[1] >= (coordinates[1] + coordinateChange[1]) >= 0):
            print("You ran onto a wall")
            return
        else:
            coordinates = [coordinates[0]+coordinateChange[0], coordinates[1]+coordinateChange[1]]

额外优化建议(可选)

你的代码依赖多个全局变量,不符合面向对象设计原则,容易引发bug。建议将这些变量转为类的实例属性,提升代码封装性:

class CoordinateManager:
    def __init__(self):
        self.coordinates = [0, 0]
        self.coordLimits = [5, 5]
        self.DTCC = {
            "left" : [-1, 0],
            "right" : [1, 0],
            "forwards" : [0, 1],
            "backwards" : [0, -1]
        }
    
    def coordinateChecker(self, direction):
        coordinateChange = self.DTCC.get(direction.lower())
        if not coordinateChange:
            return
        new_x = self.coordinates[0] + coordinateChange[0]
        new_y = self.coordinates[1] + coordinateChange[1]
        if 0 <= new_x <= self.coordLimits[0] and 0 <= new_y <= self.coordLimits[1]:
            self.coordinates = [new_x, new_y]
        else:
            print("You ran onto a wall")

调用时同步修改为:

cm = CoordinateManager()
# ...其他代码...
while True:
    print(f"Coordinates: {cm.coordinates}")
    direction = input("Enter any one of the four directions...: ")
    if direction.lower() not in ["left", "right", "forwards", "backwards", "inventory"]:
        continue
    if direction != "inventory":
        cm.coordinateChecker(direction)
        continue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:34:54