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

Python中基于列表实现含骰子对象的杯子类报错,求解决方案

代码修复方案

核心错误点及修复:

  • Dice类方法缩进错误:get_position、set_position、roll、__str__方法未缩进在Dice类内部,导致这些方法变成全局函数,无法访问实例属性。需将这些方法缩进至Dice类的代码块内。
  • Dice的__str__返回类型错误:原代码返回整数self.pos,__str__要求返回字符串,需改为return str(self.pos)。
  • Cup类实例属性赋值错误:不能直接将self赋值为列表(self是类实例本身),需创建实例属性存储骰子列表,比如self.dice = [Dice() for _ in range(num)]。
  • Cup类方法遍历对象错误:cup_roll和__str__方法中遍历self(实例对象)而非存储骰子的列表,需改为遍历self.dice。
  • 类名大小写不匹配:原类名为小写cup,测试代码中调用的是Cup,需将类名改为大驼峰Cup(符合Python类命名规范)。
  • 测试代码冗余导入:若代码在同一文件中,无需导入Dice和Cup,直接使用即可。

修复后的完整代码:

import random

class Dice:
    def __init__(self, pos=1):
        self.pos = pos
    
    def get_position(self):
        return self.pos

    def set_position(self, pos):
        self.pos = pos

    def roll(self):
        self.pos = random.randint(1, 6)
        return self
    
    def __str__(self):
        return str(self.pos)

class Cup:
    def __init__(self, num):
        self.dice = [Dice() for _ in range(num)]

    def cup_roll(self):
        for die in self.dice:
            die.roll()
        return self
    
    def __str__(self):
        return str([die.get_position() for die in self.dice])

##----------Test---------------##
LD = Cup(5)
LD.cup_roll()  # 可选:先掷骰子再打印
print(LD)

测试说明:

运行修复后的代码,会输出类似[3, 1, 5, 2, 4]的结果,符合需求。调用cup_roll()方法可一次性滚动所有骰子,重新生成随机点数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:15:37