代码之家  ›  专栏  ›  技术社区  ›  Frostbiyt

将self从成员函数传递到另一个类中的函数

  •  0
  • Frostbiyt  · 技术社区  · 2 年前

    就上下文而言,我试图在python中实现一个极小值最大算法来玩井字游戏。以下是相关代码:

    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)
    

    传入dumpPlayer函数效果很好,问题出在minimuxPlayer函数上。当play函数调用minimuxlayer函数时,我得到以下错误:
    TypeError: minimaxPlayer() missing 1 required positional argument: 'gameType' 根据我对python的理解,“self”参数是自动传递给函数的,并且不会(或者可能不能)显式传递,所以就play函数而言,
    def dumbPlayer(game, gameType)
    def minimaxPlayer(self, game, gameType)
    应该是等效的,但在这种情况下似乎不正确。

    有简单的解决方法吗?还是我需要重构我的代码?如果必须的话,我已经有了一些关于如何重组代码的想法,但我宁愿不这样做,我想知道为什么这不起作用的根本原因。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Samwise    2 年前

    这个 self 实例方法的参数会自动绑定到获取该方法的实例,但您正在访问 的版本。

    而不是:

    player2 = TTT.minimax.minimaxPlayer
    

    做:

    minimax_instance = TTT.minimax()
    player2 = minimax_instance.minimaxPlayer
    

    它应该按照你想要的方式行事。

    注意:Python中的标准约定是对类名使用CamelCase,对实例名使用snake_case,这样就不需要使用奇怪的名称,如 minimax_instance 以区分类和实例。你可能也想要 tree 成为实例属性而不是类属性(如果想法是能够在不同的游戏中使用Minimax类,你不希望不同的实例踩在彼此的状态上)。。。

    class Minimax:
        def __init__(self):
            self.tree = None
    
        def player(self, game, game_type):
            return game.successors()[0]
    
    minimax = TTT.Minimax()
    player2 = minimax.player