gpt4 book ai didi

python - Random.randint() 刷新后不工作。

转载 作者:行者123 更新时间:2023-11-28 22:53:55 30 4
gpt4 key购买 nike

我正在尝试用 python 编写简单的角色创建页面。我想要重新滚动统计信息的选项。问题是,刷新页面后,统计数据保持不变。下面是我的代码:

View .py

 from my import Character
...
def create_character():
characterform = CharacterForm()
if request.method == 'GET':
hero = Character()
hero.gen_stat()
return render_template('create_character.html', hero = hero, form = characterform)

我的.py

class Character():
def __init__(self):
self.attack = 0
self.defense = 0
self.hp = 0
self.ini = 0


def gen_stat(self,attack = randint(0,10), defense = randint(0,10), hp = randint(10,20), ini = randint(0,5)):
self.attack = attack
self.defense = defense
self.hp = hp
self.ini = ini

我现在正在学习 python,所以很可能我做错了什么。奇怪的是,如果我在几分钟后刷新,统计数据会发生变化,所以这可能与缓存有关?

请帮我解决这个问题。

最佳答案

默认参数仅计算一次(在创建函数时)。

>>> def g():
... print('g() is called')
... return 1
...
>>> def f(a=g()): # g() is called when f is created.
... pass
...
g() is called
>>> f() # g() is not called!
>>> f() # g() is not called!

替换gen_stat如下:

def gen_stat(self, attack=None, defense=None, hp=None, ini=None):
self.attack = randint(0, 10) if attack is None else attack
self.defense = randint(0, 10) if defence is None else defense
self.hp = randint(0, 10) if hp is None else hp
self.ini = randint(0, 10) if ini is None else ini

顺便说一句,根据PEP 8 -- Style Guide for Python Code :

Avoid extraneous whitespace in the following situations:

...

  • More than one space around an assignment (or other) operator to align it with another.

    Yes:

    x = 1
    y = 2
    long_variable = 3

    No:

    x             = 1
    y = 2
    long_variable = 3

关于python - Random.randint() 刷新后不工作。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18827487/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com