2014-08-31 41 views
0

這裏是我的簡單隨機模塊的內部利用我寫的簡單隨機函數發生器模塊?

from random import randint 
def randomnumget(): 
    randomnumber=randint(1,10) 
    return randomnumber 

然後,我有我的文字冒險/小遊戲,其中包括代碼來測試隨機數是什麼。 (我知道它的重複性,這可能意味着我需要稍後重構)

class charactercreator: 
    def characterget(self, randomnumber): 
     if randomnumber==1: 
      print'your hero is dumbledore' 
     elif randomnumber==2: 
      print 'your hero is ruthless pantheon' 
     elif randomnumber ==3: 
      print 'your hero is Percy Jackson' 
     elif randomnumber==4: 
      print 'your hero is hagrid' 
     elif randomnumber==5: 
      print 'your hero is Ingrid Michaelson, Good luck sonny' 
     elif randomnumber==6: 
      print 'your hero is The incredible hulk' 
     elif randomnumber==7: 
      print 'your hero is captain america' 
     elif randomnumber==8: 
      print 'your hero is peter pan' 
     elif randomnumber==9: 
      print 'your hero is catwoman' 
     elif randomnumber==10: 
      print 'your hero is captain hook' 
     else: 
      print('how did you even manage to get this output') 

numget=charactercreator() 

如何有效地利用我的模塊?

+0

哦,上帝的編輯讓我看起來像這樣的笨蛋。謝謝你elmatrak。 – 2014-08-31 15:30:17

回答

2

看起來像characterget應替換爲一個簡單的字典。

characterget = {1: 'your hero is dumbledore', 
       2: 'your hero is ruthless pantheon', ...} 

,只是使用它:

print characterget.get(randomnumget(), 
         'how did you even manage to get this output') 
0

比方說,你的隨機碼是randomizer.py在同一個包(文件夾與__init__.py文件吧)

from randomizer import randomnumget 
numget = charactercreator() 
numget.characterget(randomnumget()) 

我建議你閱讀official documentation on Python modules