2014-03-12 66 views
0

我有2個文件被導入到主文件,並且運行。'AttributeError:'模塊'對象沒有屬性'randomVariable''

當我運行它,我不斷收到錯誤:

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() 

有什麼問題?

+1

你在交互式解釋嘗試這種?如果是這樣,請重新啓動它(並確保您將文件保存在編輯器中)。解釋器緩存模塊,並在導入時重用它們,因此不會收到更改。 –

+0

我做到了,但仍然出現錯誤。 – user3092741

+0

我無法在我的機器上重現問題 - 在main()函數內部打印dir(random_var)並粘貼輸出 – dannymilsom

回答

1

最有可能的解釋是random_var不是你認爲的那樣。

如果您在交互式解釋器中運行此操作,請關閉並重新啓動它,以確保重新裝入模塊。

除此之外,請確保您保存random_var.py,其文件名是否正確(包括大小寫),並且它一直保存在那裏import random_var正在尋找它(即您還沒有結束了兩個random_var.py文件在不同的目錄中)。

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() 
+0

我試過了,但它只是想出了錯誤'ImportError:can not import name randomVariable' – user3092741

+0

都是在同一個目錄下的文件嗎? –

+0

是的,他們是。 。 – user3092741

相關問題