I'm trying to write, simple character creation page in python. I want option to reroll stats. The problem is that, after refreshing the page, stats stay the same. Below is my code:
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
I'm learning python right now, so propably I'm doing something wrong. The weird thing is that, if I refresh after few minutes, the stats change, so maybe it's related to caching?
Please help me solve this.
Default parameters are evaluated only once (when the function is created).
>>> 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!
Replace gen_stat
as follow:
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, According to 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.