以下是我的简单随机数发生器模块的内容
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 :(得分: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')
答案 1 :(得分:0)
假设您的随机数发生器代码位于randomizer.py
的同一个包中(其中包含__init__.py
文件的文件夹)
from randomizer import randomnumget
numget = charactercreator()
numget.characterget(randomnumget())