当只有1个类被实例化时,如何在2个类之间共享变量?

问题描述 投票:0回答:1

所以我有2个python文件,main.py是主文件,web.py包含web应用程序代码(使用Tornado)。所以在web.py中,我想在主Web应用程序类(WebAppModule,在main.py中实例化)和另一个类(WSHandler,它从客户端处理WebSocket连接)之间共享变量。但是,我能想到的唯一方法是使用全局变量(如下面通过is_button_clicked变量所示)。有没有其他方法可以做到这一点?

卖弄.朋友:

from web import WebAppModule

web_client = WebAppModule(9000)  

Web.朋友:

clients = []
wsThread = None
is_button_clicked = None

class WebAppModule():
    def __init__(self,portnumber):
        global is_button_clicked
        is_button_clicked = False
        self.process_running = ""
        self.connection_open = False

    def some_other_function:
        pass


class MyStaticFileHandler(tornado.web.StaticFileHandler):
    def set_extra_headers(self, path):
        self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('web/index.html')


class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        if len(clients)==0:
            clients.append(self)
            print 'web app connection opened...'
        else:
            print 'Another client already accessed the UI. Connection blocked...'

    def check_origin(self, origin):
        return True

    def on_message(self, message):
        for client in clients:    
            if "BUTTON_CLICKED" in message:
                global is_button_clicked
                is_button_clicked = True

    def on_close(self):
        try:
            clients.remove(self)
            print 'connection closed...'
        except Exception, e:
            print "Client not established. Skipped..."


settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "web"),
    "static_hash_cache": False,
}    

application = tornado.web.Application([
    (r'/ws', WSHandler),
    (r'/', MainHandler),
], static_path=os.path.join(os.path.dirname(__file__), "web"), static_handler_class=MyStaticFileHandler)
python tornado
1个回答
0
投票

您需要使用可变对象。字符串不可变。原因是python只评估一次,因此在运行期间,整个应用程序都会更改任何可更改的可变字符串。

shared = {'wsThread':None,
          'is_button_clicked':None
         }

然后在def中更新:

def set(self, value):
    shared['is_button_clicked'] = value

def get(self):
    return shared['is_button_clicked']
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.