首页 > 解决方案 > 为什么我的错误是说我试图调用的属性不存在?

问题描述

首先,我是一个完整的初学者,很抱歉提出这个基本问题,但我一直坚持下去。我正在尝试创建一个骰子滚轮,它将生成两个六面骰子的总和(所以基本上它会生成一个介于 2-12 之间的数字)。这是我的代码:

def dice(): 
    import random
    first = random.randint(1, 6)
    second = random.randint(1, 6)
    roll = first + second 

但是,当我打电话时< dice.roll >,我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'dice' has no attribute 'roll'

当我在代码的最后一行定义 roll 时,为什么说我的模块 'dice' 没有属性 'roll'?我觉得这有一个简单的原因,但我就是想不起来。

标签: pythonattributesattributeerrordice

解决方案


您创建了一个函数。函数只能使用它们的名称运行,例如dice(). 但是你的函数实际上并没有返回任何东西。

你可以return roll在最后一行做。或return first+second

所以像这样


def dice(): 
    import random
    first = random.randint(1, 6)
    second = random.randint(1, 6)
    roll = first + second
    return roll

那你可以试试print(dice())

或者,如果您想创建一个具有滚动功能的骰子对象。您首先需要创建一个骰子类并在骰子类中定义一个滚动函数。

一个例子是这样的

import random

class Dice():
    def __init__(self, dice = 1):
        self.dice = dice
        self.result = 0

    def roll(self):
        for i in self.dice:
            self.result += random.randint(1, 6)
    
    def get_result(self):
        print(self.result)

然后你可以动态创建更多的骰子,

可以这样开始

dice = Dice(2) #creates dice object with 2 dice
dice.roll() #will roll the 2 dice and store the result in roll
dice.get_result() #will print the result

你也可以像这样创建它

import random

class Dice():
    def __init__(self, dice = 1):
        self.dice = dice
        self.result = 0

    def roll(self):
        for i in self.dice:
            self.result += random.randint(1, 6)
        print(self.result)

然后你可以像这样运行它,

dice = Dice(2) #creates dice object with 2 dice
dice.roll() #will roll the 2 dice and print the result


推荐阅读