Python类中如何在一个方法内访问另一个方法的变量?
解决井字棋类方法间的坐标访问问题
你的核心问题是局部变量的作用域限制,同时存在类方法定义和语法的几个小错误,下面一步步修正:
1. 修正getMove方法:返回坐标而非字符串,修复输入验证逻辑
getMove里的xcoor和ycoor是局部变量,只能在该方法内部使用。要让其他方法拿到这两个值,直接返回坐标(而非格式化字符串)是更合理的方案。另外原输入验证逻辑存在逻辑漏洞,需要分别判断x和y的合法性:
def getMove(self): print("Coordinates must range from 0 to 2, 0 corresponding to the first row/column, onwards") while True: xcoor = int(input("What is your x coordinate?")) ycoor = int(input("What is your y coordinate?")) # 分别校验x、y是否在合法范围 if xcoor not in range(3) or ycoor not in range(3): print("Coordinates must be between 0 and 2, try again") else: # 返回两个整数坐标,方便其他方法直接使用 return xcoor, ycoor
2. 修正makeMove方法:改为标准类方法,完成落子逻辑
作为类的方法,makeMove必须带self参数,才能调用类内的其他方法(比如getMove)。同时注意用赋值运算符=而非比较运算符==来修改棋盘:
def makeMove(self, board, marker): # 调用getMove获取合法坐标 xcoor, ycoor = self.getMove() # 执行落子操作(用=赋值,不是==比较) board[xcoor][ycoor] = marker
3. 类的完整调用示例
假设你的TicTacToe类初始化时创建空棋盘,完整调用逻辑如下:
class TicTacToe: def __init__(self): # 初始化3x3空棋盘 self.board = [[" " for _ in range(3)] for _ in range(3)] def getMove(self): print("Coordinates must range from 0 to 2, 0 corresponding to the first row/column, onwards") while True: xcoor = int(input("What is your x coordinate?")) ycoor = int(input("What is your y coordinate?")) if xcoor not in range(3) or ycoor not in range(3): print("Coordinates must be between 0 and 2, try again") else: return xcoor, ycoor def makeMove(self, marker): xcoor, ycoor = self.getMove() self.board[xcoor][ycoor] = marker # 打印更新后的棋盘 for row in self.board: print(row) # 测试游戏流程 game = TicTacToe() game.makeMove("X") game.makeMove("O")
关键知识点梳理
- 局部变量作用域:函数内部定义的变量只能在函数内访问,若要跨方法使用,要么通过返回值传递,要么用
self.xcoor = xcoor将其设为实例属性。 - 类方法规范:类中的方法必须以
self作为第一个参数,通过self可以访问实例的属性和其他方法。 - 运算符区分:
=用于赋值,==用于判断相等,二者不可混淆。
内容的提问来源于stack exchange,提问作者n00bcoder_24
相关产品推荐
相关产品推荐

