如何在Python中同一类的方法之间传递变量 [英] How to pass variables between methods in the same class in Python

查看:162
本文介绍了如何在Python中同一类的方法之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我没有正确使用类变量.在ClientFormPage类中,我将active_form初始化为'f1_form'.发布第一个表单后,我想将active_form推进到"f2_form",但是它将一直重置为"f1_form".最好的方法是什么?

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

推荐答案

如果我理解您的代码并很好地注释,则您希望保留请求之间的状态(active_form).为此,您必须使用Cookie.

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.

在两次请求之间,您无法在webapp2请求处理程序类中保存状态.对于每个请求,都会创建一个新的处理程序类.

You cannot save state in your webapp2 request handler class between requests. For every request a new handler class is created.

请参阅文档: http://webapp-improved.appspot. com/api/webapp2_extras/sessions.html

另一种方法是将活动表单的名称保存在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 }}" >

这篇关于如何在Python中同一类的方法之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆