问题
I don't think I'm using class variables correctly. Inside the ClientFormPage class, I initialize the active_form to 'f1_form'. After I post the first form, I'd like to advance the active_form to 'f2_form', however it keeps resetting to 'f1_form'. What is the best way to do this?
class ClientFormPage(PageHandler):
active_form = 'f1_form'
def render_form(self, f1='hidden', f2='hidden', **kw):
self.render('clientforms.html', form1=f1, form2=f2, **kw)
def get(self):
self.render_form(f1='')
def get_form2(self):
self.render_form(f2='')
def post(self):
if self.active_form == 'f1_form':
foo = self.request.get('foo')
if not foo:
self.render_form(f1_form='', foo=foo,
foo_error='has-error has-feedback')
else:
self.active_form = 'f2_form' # This assignment is not sticking
self.get_form2()
return
if self.active_form == 'f2_form':
bar = self.request.get('bar')
if not bar:
self.render_form(f1_form='', bar=bar,
bar_error='has-error has-feedback')
else:
self.active_form = 'f3_form'
self.get_form3()
return
回答1:
If I understand your code and comment well, You want to preserve state (active_form) between requests. To do this you have to use cookies.
You cannot save state in your webapp2 request handler class between requests. For every request a new handler class is created.
See the docs: http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html
An alternative approach is to save the name of your active form in a hidden input of your HTML form.
<input type="hidden" name ="active_form" value="{{ active_form }}" >
回答2:
You could use the __init__
magic method
class ClientFormPage(PageHandler):
def __init__(self):
self.active_form = 'f1_form'
This will allow you to have instance specific attributes, instead of class attributes as you have in your original code.
Quick demo on the difference:
Python - why use "self" in a class?
回答3:
class myClass(object):
def __init__(self):
def helper(self, jsonInputFile):
values = jsonInputFile['values']
ip = values['ip']
username = values['user']
password = values['password']
return values, ip, username, password
def checkHostname(self, jsonInputFile):
values, ip, username, password = self.helper
print values
print '---------'
print ip
print username
print password
the init method initializes the class. the helper function just holds some variables/data/attributes and releases them to other methods when you call it. Here jsonInputFile is some json. the checkHostname is a method written to log into some device/server and check the hostname but it needs ip, username and password for that and that is provided by calling the helper method.
来源:https://stackoverflow.com/questions/23051746/how-to-pass-variables-between-methods-in-the-same-class-in-python