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

Python运行掷骰子判定代码报错'list' object has no attribute 'countPoints'如何解决

报错根因

'list' object has no attribute 'countPoints' 报错的核心是调用方法的对象类型不匹配:

  • 你代码中调用countPoints()的rollPlayerA、rollPlayerB都是Python原生列表类型,原生列表没有内置countPoints方法
  • 该方法是你定义在ModuleRollDice模块中的自定义函数,不能直接作为列表的属性调用

另外你的代码还存在语法问题:跨换行的if判断条件没有加续行符\,修复方法调用问题后也会触发语法报错,需要同步处理。

修复方案

方案1:调整方法调用逻辑(最简便)

将列表对象.countPoints(参数)的写法调整为从导入的dce模块调用,将列表作为第一个参数传入即可,同时补充续行符修复语法问题:

import ModuleRollDice as dce

def judge(rollPlayerA,rollPlayerB):
    if not all(item in dce.options for item in rollPlayerA) or \
       not all(item in dce.options for item in rollPlayerB):
            print("error")

    if dce.countPoints(rollPlayerA, rollPlayerA[0]) == len(rollPlayerA) and \
       dce.countPoints(rollPlayerB, rollPlayerB[0]) != len(rollPlayerB):
            return "A"

    if dce.countPoints(rollPlayerA, rollPlayerA[0]) != len(rollPlayerA) and \
       dce.countPoints(rollPlayerB, rollPlayerB[0]) == len(rollPlayerB):
            return "B"

    elif sum(rollPlayerA) == sum(rollPlayerB):
        return "tie"

    elif sum(rollPlayerA) > sum(rollPlayerB):
        return "A"

    else:
        return "B"

方案2:保留原调用写法

如果需要保持列表对象.countPoints()的调用方式,可以自定义继承原生列表的子类,将countPoints作为类方法实现:

  1. 在ModuleRollDice.py中新增自定义类:
class DiceResult(list):
    def countPoints(self, target):
        # 此处替换为你原countPoints函数的业务逻辑即可
        return self.count(target)
  1. 生成rollPlayerA、rollPlayerB时,用DiceResult(普通列表)做一层类型转换,即可沿用原调用写法。

额外优化方案

如果你的countPoints功能就是统计指定元素在列表中的出现次数,完全可以直接用Python列表内置的count()方法,无需自定义函数,直接将代码中所有countPoints替换为count即可直接运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 03:54:03