Python调用dice.roll报AttributeError属性不存在是什么原因?
骰子投掷工具代码错误解答
错误原因
- 你混淆了Python中函数局部变量、对象属性的概念:你定义的
dice是普通函数,函数内部定义的roll属于函数执行时才生效的局部变量,不属于函数的属性,无法通过函数名.变量名的格式直接访问。 - 你的
dice函数没有设置返回值,即使正常调用函数也无法拿到两个骰子的点数求和结果。 - 报错提示
module 'dice' has no attribute 'roll'说明你将代码保存为了名为dice.py的文件,执行导入操作时Python优先识别到dice为模块对象,而非你定义的同名函数,模块中没有roll属性因此抛出错误。
修复方案
方案1:普通函数实现(最匹配你的需求)
将random模块导入移到文件顶部,函数直接返回求和结果,调用函数即可获得2~12的随机整数:
import random def dice(): first = random.randint(1,6) second = random.randint(1,6) return first + second # 调用示例 print(dice())
方案2:类实现(支持通过.roll方法调用)
如果你需要通过类似.roll的格式调用功能,可以定义骰子类实现:
import random class Dice: def roll(self): first = random.randint(1,6) second = random.randint(1,6) return first + second # 调用示例 dice_tool = Dice() print(dice_tool.roll())
内容的提问来源于stack exchange,提问作者Chris Lee
相关产品推荐
相关产品推荐

