提问人:Frostbiyt 提问时间:6/2/2023 更新时间:6/2/2023 访问量:16
将 self 从成员函数传递到另一个类中的函数 [duplicate]
Passing self from a member function to a function in another class [duplicate]
问:
对于上下文,我正在尝试在 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 函数上。当 play 函数调用 minimaxPlayer 函数时,我收到以下错误:
根据我对 python 的理解,“self”参数会自动传递给函数,并且不会(或可能无法)显式传递,因此就 play 函数而言,应该是
等效的,
但在这种情况下似乎是不正确的。TypeError: minimaxPlayer() missing 1 required positional argument: 'gameType'
def dumbPlayer(game, gameType)
def minimaxPlayer(self, game, gameType)
有没有简单的解决方法?或者我需要重构我的代码吗?我已经有一些想法,如果有必要,我将如何重构代码,但我宁愿不要,我想知道为什么这不能像我预期的那样工作。
答:
实例方法的参数会自动绑定到从中获取该方法的实例,但您正在访问该方法的类版本。self
而不是:
player2 = TTT.minimax.minimaxPlayer
做:
minimax_instance = TTT.minimax()
player2 = minimax_instance.minimaxPlayer
它应该按照你想要的方式运行。
注意:Python 中的标准约定是使用 CamelCase 作为类名,snake_case 作为实例名,这样就不需要使用奇怪的名称来区分类和实例。您可能还希望成为实例属性而不是类属性(如果想法是能够在不同的游戏中使用 Minimax 类,您不希望不同的实例相互踩踏彼此的状态)......minimax_instance
tree
class Minimax:
def __init__(self):
self.tree = None
def player(self, game, game_type):
return game.successors()[0]
minimax = TTT.Minimax()
player2 = minimax.player
评论
minimax
的实例 - 在该代码中将被称为 - 以便能够使用该代码 - 对吗?所以。如果我们只是说,实例在哪里?TTT.minimax.minimaxPlayer
minimaxPlayer
self
TTT.minimax.minimaxPlayer