'AttributeError:'模块'对象没有属性'randomVariable''

时间:2014-03-12 10:46:18

标签: python

我有2个文件导入到主文件中,然后运行。

当我运行它时,我不断收到错误:

dice_sides = random_var.randomVariable()
AttributeError: 'module' object has no attribute 'randomVariable'
>>> 

我的代码:主文件:

import random, random_var, dice_roll

dice = [4, 6, 12]

def main():
    dice_sides = random_var.randomVariable()
    dice_roll.diceRoll(dice_sides)

main()

Random_var文件:

import random, task_one # import modules and file to be used in program

dice = [4, 6, 12] # declare list

def randomVariable(): # function

    try: # tries this expression
        dice_sides = int(input("Please enter the amount of sides you want the dice that is being thrown to have. The sides available are: 4, 6 and 12: "))
    except ValueError: # if user entered anything other than an integer
        print("You did not enter an integer. Program restarting.")
        task_one.main() # restarts, by getting the main function from "task_one" file

    return dice_sides; # returns variable so it can be used in other functions

Dice_roll文件:

import random, task_one

dice = [4, 6, 12]
def diceRoll(dice_sides):

    if dice_sides in dice:
        diceThrown = random.randrange(1, dice_sides)
        print(dice_sides, " sided dice, score ", diceThrown)
    else:
        print("Number is invalid. Please choose either 4, 6 or 12. ")
        task_one.main()

有什么问题?

2 个答案:

答案 0 :(得分:1)

最可能的解释是random_var不是您认为的。

如果您在交互式解释器中运行它,请关闭并重新启动它以确保模块重新加载。

除此之外,请确保您已保存random_var.py,其文件名正确(包括大写),并且已保存import random_var正在查找的位置(即你还没有在不同的目录中找到两个random_var.py个文件)。

答案 1 :(得分:0)

您可以尝试:

import random
from random_var import randomVariable
from dice_roll import diceRoll

dice = [4, 6, 12]

def main():
    dice_sides = randomVariable()
    diceRoll(dice_sides)

main()