python - 如何使用 python (3.2) 保存函数

标签 python function python-3.x

刚开始学python(3.2),有疑问。我创建了一些代码来创建一些统计数据(如健康、魔法等),并且数字是随机生成的。这是代码...

def stats ():
print ()
print ('Some text.')

done = False
while not done :
charname = input(str('What is the name of the character? '))

hp = random.randint(5,20)
mp = random.randint(4,20)
stre = random.randint(3,20)
agi = random.randint(3,20)
spd = random.randint(3,20)
wis = random.randint(3,20)
intel = random.randint(3,20)
cha = random.randint(3,20)

print (charname)
print ('HP:',hp)
print ('Mana:',mp)
print ('Strength:',stre)
print ('Agility:',agi)
print ('Speed:',spd)
print ('Wisdom:',wis)
print ('Intelligence:',intel)
print ('Charisma:',cha)
print ()


done = input('All done? yes/no ')
if( done == 'yes' ):
    done = True
elif(done == 'no'):
    done = False



while done :
print ()
print ('Now that your stats are done, you can go on your adventure!')
done = False

现在这很好用了,但是如果我想再次查看统计数据并保持之前随机生成的相同统计数据,我怎么能再次调用这个函数呢?

抱歉,如果问题有点不对。还是编程新手。

谢谢。

最佳答案

由于您是编程新手,这里有一些关于存储数据的不同方式的建议(无需实际为您编码)。

首先,定义一个Character类,带有HP、法力等属性。我不知道你是否了解类,但是here's an intro .您可以使用各种技巧来避免必须明确写入 HP、法力等名称,但为了学习起见,目前最好手动完成这些操作。

然后 def 一个 random_character() 函数创建一个具有随机属性的 Character 对象,定义就像你现在做的那样,但是不是将它们保存在 Python 不知道彼此有任何关系的不同变量中,而是将它们放在一个 Character 中。

Character类中添加一个__str__方法,这样如果char是一个Characterprint(char) 打印出属性。

如果您希望能够跟踪字符,请使用 pickle将其存储在文件中。

如果您对此有任何疑问,请尽管提问。 :)

关于python - 如何使用 python (3.2) 保存函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11588934/

相关文章:

c - 幂函数 K&R

javascript 函数作为参数 - 非法调用。为什么?

javascript - 如何避免在 ES6 : const that = this when scope nested in React 中创建 'this' 的引用

python - 从配置文件自定义 python 结构化 (json) 日志记录中的键值

python - 使用正则表达式时得到不正确的匹配

python - 如何将图像放大到特定点 + 缩放后跟踪特定点

python - 使用 sqlalchemy 等待行更新或行插入

python - 检查相同条件下的多个 hasattr

python - 如何通过使用将参数保留在同一列中的第一个和最后一个来删除 pandas df 列中的重复值

python - 在python中创建matlab平均滤波器