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

Python在线练习求助:完成Case类与Terrain类实现,重点解决__str__方法问题

解决你的井字棋Terrain类__str__方法及代码问题

嘿,作为Python新手能写到这一步已经很棒了!咱们一步步来梳理和修正你的代码,先解决__str__方法的问题,再把其他小细节也调整好。

首先修正Case类的小问题

你的Case类__init__方法里定义了occupe参数,但实际上没有用到它,直接把self.occupe赋值为' '了,所以可以把这个多余的参数去掉:

class Case:
    def __init__(self):  # 去掉无用的occupe参数
        self.occupe = ' '
    def jouer1(self):
        if self.occupe == ' ':
            self.occupe = 'X'
    def jouer2(self):
        if self.occupe == ' ':
            self.occupe = 'O'

修正Terrain类的__init__方法

现在你的Terrain__init__里grille是数字列表,这不符合要求——grille应该是9个Case类的实例。而且tour参数也可以去掉,因为实例化时要自动初始化为1:

class Terrain():
    def __init__(self):
        # 创建包含9个Case实例的列表
        self.grille = [Case() for _ in range(9)]
        self.tour = 1  # 初始化为玩家1的回合

实现符合要求的__str__方法

__str__方法的核心是返回一个字符串,而不是直接print内容(因为print(obj)本质是打印obj.__str__()返回的字符串)。我们可以把网格分成三行,每行取3个Case的occupe属性,用'|'连接,然后把三行用换行符拼接起来:

def __str__(self):
        # 构建每行的字符串
        line1 = " | ".join([case.occupe for case in self.grille[0:3]])
        line2 = " | ".join([case.occupe for case in self.grille[3:6]])
        line3 = " | ".join([case.occupe for case in self.grille[6:9]])
        # 把三行用换行符连接起来返回
        return f"{line1}\n{line2}\n{line3}"

这样当你print一个Terrain对象时,就会输出:

|   |   
   |   |   
   |   |   

当有玩家落子后,就会变成类似:

X |   | O
   | X |   
   |   |   

补充实现play方法

你还没完成play方法,这里也一起写出来,逻辑是:检查格子是否合法(0-8),然后根据当前回合调用对应Case的方法,最后切换回合:

def play(self, position):
        # 先检查位置是否合法
        if not 0 <= position <= 8:
            print("位置无效,请输入0-8之间的数字!")
            return
        current_case = self.grille[position]
        # 根据当前回合调用对应方法
        if self.tour == 1:
            current_case.jouer1()
            # 切换到玩家2回合
            self.tour = 2
        else:
            current_case.jouer2()
            # 切换到玩家1回合
            self.tour = 1

测试一下代码

你可以用下面的代码测试整个逻辑:

# 创建Terrain实例
game = Terrain()
print("初始棋盘:")
print(game)

# 玩家1在位置0落子
game.play(0)
print("\n玩家1落子后:")
print(game)

# 玩家2在位置2落子
game.play(2)
print("\n玩家2落子后:")
print(game)

运行后会输出符合要求的棋盘格式。

总结一下你之前__str__方法的问题

  1. __str__方法需要返回字符串,而不是直接print,你之前的代码里混合了return和print,逻辑混乱;
  2. 没有正确访问grille里的Case对象的occupe属性,而是直接操作数字;
  3. 循环和字符串拼接的逻辑错误,导致无法正确生成三行格式。

这样调整后,你的代码就能完全符合练习要求啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 21:12:40