开发者

How to initialize empty list?

Every time the input s comes from the form; the list is initialized again. How do I change the code to append each new s to the list?

Thank you.

class Test(webapp.RequestHandler):
    def get(self):

        s = self.request.get('sentence')
        list = []                                   
   开发者_开发百科     list.append(s)                      
        htmlcode1 = HTML.table(list)        


I'm not sure what the context of your code is, but this should work:

class Test(webapp.RequestHandler):
    def get(self):
        s = self.request.get('sentence')
        try:
            self.myList.append(s)
        except NameError:
            self.myList= [s]
        htmlcode1 = HTML.table(self.myList)

This makes list an instance variable so it'll stick around. The problem is that list might not exist the first time we try to use it, so in this case we need to initialize it.

Actually, looking at this post, this might be cleaner code:

class Test(webapp.RequestHandler):
    def get(self):
        s = self.request.get('sentence')
        if not hasattr(self, 'myList'):
            self.myList = []
        self.myList.append(s)
        htmlcode1 = HTML.table(self.myList)

[Edit:] The above isn't working for some reason, so try this:

class Test(webapp.RequestHandler):
    myList = []
    def get(self):
        s = self.request.get('sentence')
        self.myList.append(s)
        htmlcode1 = HTML.table(self.myList)


You could make the list a member variable of the object and then only update it when get() is called:

class Test(webapp.RequestHandler):
    def __init__(self, *p, **kw): # or whatever parameters this takes
        webapp.RequestHandler.__init__(self, *p, **kw)
        self.list = []

    def get(self):
        s = self.request.get('sentence')
        self.list.append(s)                      
        htmlcode1 = HTML.table(self.list)        
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜