2

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

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

请帮我解决这个问题。

4

1 回答 1

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

顺便说一句,根据PEP 8——Python 代码样式指南

在以下情况下避免多余的空格:

...

  • 赋值(或其他)运算符周围有多个空格,以将其与另一个对齐。

    是的:

    x = 1
    y = 2
    long_variable = 3
    

    不:

    x             = 1
    y             = 2
    long_variable = 3
    
于 2013-09-16T12:05:21.473 回答