无法从WebSocket服务器访问类变量

时间:2014-03-12 03:01:27

标签: python variables websocket

所以我试图从Progressive类中获取渐进量。但是,我已经尝试了很多次从WebSocket类访问它,但不能。这里有什么问题?

谢谢!

from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer

class Progressive():
    def __init__(self):
        self.progressive = 0

    def affect(self, amt):
        self.progressive += amt


class SimpleEcho(WebSocket):
    progressive = Progressive()

    def handleMessage(self):
        if self.data is None:
            self.data = ''

        # echo message back to client
        self.sendMessage(str(self.data))

        print 'Sent back', str(self.data)

    def handleConnected(self):
        print self.address, 'connected'
        print progressive.progressive

    def handleClose(self):
        print self.address, 'closed'

server = SimpleWebSocketServer('', 8000, SimpleEcho)
server.serveforever()

1 个答案:

答案 0 :(得分:2)

您在类范围内声明progressive,但尝试引用它,就好像它在本地范围内定义一样。您需要在其前面添加selfSimpleEcho

class SimpleEcho(WebSocket):
    progressive = Progressive()

    def handleConnected(self):
        print self.address, 'connected'
        print self.progressive.progressive

您的Progressive课程存在同样的问题。请注意,affect应使用初始self参数定义,因为它不是staticmethod

class Progressive():
    progressive = 0

    def affect(self, amt):
        self.progressive += amt

<强>无论其!

您在此处所做的事情意味着 Progressive的每个实例都会修改相同的 progressive属性(并且每个{同上} {1}}实例)。您可能想要做的是在初始化实例时在两个类上声明SimpleEcho属性:

progressive