刷新后Random.randint()不起作用。

时间:2013-09-16 12:00:25

标签: python flask

我正在尝试在python中编写简单的字符创建页面。我想要选择重新统计数据。问题是,刷新页面后,统计数据保持不变。以下是我的代码:

Views.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)

my.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,所以我做错了。奇怪的是,如果我在几分钟后刷新,统计数据会发生变化,那么它可能与缓存有关吗?

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:4)

默认参数仅评估一次(创建函数时)。

>>> 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

BTW,根据PEP 8 -- Style Guide for Python Code

  

在以下情况下避免无关的空白:

     

...

     
      
  • 分配(或其他)运算符周围的多个空格,以使其与另一个运算符对齐。

         

    是:

    x = 1
    y = 2
    long_variable = 3
    
         

    否:

    x             = 1
    y             = 2
    long_variable = 3
    
  •