0

A simpilified code is as follow:

....

class indexHandler(tornado.web.RequestHandler):
    a=[]

    def callback(self,response):
        #Do some other things, like write into database
        self.a=[]


    def get(self):
        print self.a
        self.a.append('abc')

        client=tornado.httpclient.AsyncHTTPClient()
        client.fetch('http://google.com',self.callback)

        self.write('OK')
        ....

When I visit the page first time, the shell shows []. after page reload, it shows ['abc'], reload once more then it shows ['abc','abc'] and so on.

Why the a wouldn't reset?

MK Yung
  • 4,344
  • 6
  • 30
  • 35
  • 2
    Because `a` is not an instance attribute, but a *class* attribute. It is shared among all instances. – Martijn Pieters Feb 23 '13 at 15:12
  • Looking for the canonical question to link you to because this is being asked *all the time*. I hesitate to link you to ["Least Astonishment" in Python: The Mutable Default Argument](http://stackoverflow.com/q/1132941) though. – Martijn Pieters Feb 23 '13 at 15:15
  • there are two variables. the former one is the class variable a (accessable using indexHandler.a), the other is the instance variable (accessable using self.a). both have nothing in common. – mkind Feb 23 '13 at 15:15

1 Answers1

1

Thanks both Martijn and mkind! You all are right, I used __init__ and it solves the problem.

Substitute a=[] with

def initialize(self):
    self.a=[]

would fix the problem.

Note that def __init__(self) alone does not work, Tornado provides the initialize function to substitute it. Read here: python/tornado – Why am I getting this error?

Community
  • 1
  • 1
MK Yung
  • 4,344
  • 6
  • 30
  • 35