2014-12-05 104 views
-4

我在使用隨機模塊時遇到了麻煩,因爲我在類中使用randint,它似乎無法訪問隨機模塊。這應該如何處理?python:'rand'沒有定義,在類中隨機使用

from random import random 

class Pursuer(): 
    X_tally = 0 
    Y_tally = 0 

    def __init__(self):  


    def roll_pursue_type(self): 
     self.pursue_dice = rand.randint(1,100) 
     print(self.pursue_dice) 

回溯:線12,在roll_pursue_type self.pursue_dice = rand.randint(1100) NameError:名稱 '蘭特' 沒有定義

+0

'從隨機導入randint self.pursue_dice = randint(1100)'有沒有蘭特 – 2014-12-05 10:41:43

+0

使用 進口隨機作爲蘭德這樣的事情蘭特 – nishparadox 2014-12-05 10:42:34

回答

2

該模塊稱爲random,不rand,但你沒有正確導入:

# Import the *module*, not the function 
import random 

# Use the correct name in your method 
self.pursue_dice = random.randint(1,100) 

聲明from random import random只導入一個參考random.random() function,而不是模塊本身。您正試圖在該模塊上使用不同的函數,因此可以更輕鬆地導入整個模塊對象。

可以導入模塊以另一個名字太:

# Still importing the *module*, not the function, but renaming it 
import random as rand 

# using the new name in your method 
self.pursue_dice = rand.randint(1,100) 
0

您已經導入random,不rand(加,你只導入了隨機函數從隨機模塊)

所以要麼使用import random,要麼使用random.randint(),或者您可以在導入時隨機重命名:

import random as rand 
0

進口隨機如蘭特

self.pursue_dice = rand.randint(1100)

只是使用Python作爲操作者隨機如蘭特

相關問題