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

Python中Minimax类成员函数传参报错,求原因及简便修复方案

问题:MinimaxPlayer调用时出现参数缺失错误

场景与代码

我正在Python中实现用于井字棋的Minimax算法,相关代码如下:

TicTacToe.py

def dumbPlayer(game, gameType):
    return game.successors()[0]


class minimax:
    tree = None
    def minimaxPlayer(self, game, gameType):
        return game.successors()[0]


class TicTacToe:
    def play(self, xPlayer=consolePlayer, oPlayer=consolePlayer, output=consolePrint):
        while self.winner is None:
            output(self)
            if self.turn == 'X': self.move(xPlayer(self, TicTacToe))
            elif self.turn == 'O': self.move(oPlayer(self, TicTacToe))
        output(self, True)
        return

main.py

import TicTacToe as TTT

player2 = TTT.minimax.minimaxPlayer
test = TTT.TicTacToe()

test.play(TTT.dumbPlayer, player2)

错误现象

传入dumbPlayer函数可正常运行,但调用minimaxPlayer函数时出现错误:

TypeError: minimaxPlayer() missing 1 required positional argument: 'gameType'

我原本以为def dumbPlayer(game, gameType)和def minimaxPlayer(self, game, gameType)在play函数看来是等价的,因为self参数会自动传递,但实际并非如此。想知道:

  1. 报错的根本原因是什么?
  2. 是否有无需重构代码的简便修复方法?

解答

根本原因

dumbPlayer是独立函数,调用时直接接收传入的两个参数(game和gameType)。而minimaxPlayer是类的实例方法,它的第一个参数self需要绑定到类的实例才能自动传递。你现在直接取TTT.minimax.minimaxPlayer,拿到的是未绑定的方法对象,调用时不会自动传入self,此时play函数传入的游戏实例会被当作minimaxPlayer的self参数,原本的gameType参数就缺失了,所以触发报错。

无需重构的修复方法

有两种简单的解决方式:

方法1:创建minimax类的实例,使用绑定后的方法

修改main.py中的代码:

import TicTacToe as TTT

# 创建minimax类的实例
minimax_instance = TTT.minimax()
# 此时minimax_instance.minimaxPlayer是绑定了实例的方法,self会自动传入
player2 = minimax_instance.minimaxPlayer
test = TTT.TicTacToe()

test.play(TTT.dumbPlayer, player2)

方法2:将minimaxPlayer改为静态方法或类方法

如果当前minimaxPlayer不需要访问类的实例属性(比如代码里的tree),可以修改方法类型:

静态方法(无需访问类/实例属性)

修改TicTacToe.py中的minimax类:

class minimax:
    tree = None
    @staticmethod
    def minimaxPlayer(game, gameType):
        return game.successors()[0]

静态方法不需要self参数,调用逻辑和普通函数完全一致,直接通过TTT.minimax.minimaxPlayer即可使用。

类方法(需访问类属性时用)

如果后续需要访问类级别的属性(比如tree),可以改成类方法:

class minimax:
    tree = None
    @classmethod
    def minimaxPlayer(cls, game, gameType):
        # 用cls访问类属性,比如cls.tree
        return game.successors()[0]

类方法的第一个参数是类本身(cls),调用时会自动绑定,同样可以直接通过类名调用。


内容的提问来源于stack exchange,提问作者C-J-B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:35:21