Alec
Alec

Reputation: 979

Can't Access Class Variable From WebSocket Server

So I am trying to get the amount from progressive in the Progressive class. However, I have tried so many times to access it from the WebSocket class, but can't. What's wrong here?

Thanks!

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()

Upvotes: 0

Views: 166

Answers (1)

Matthew Trevor
Matthew Trevor

Reputation: 14961

You're declaring progressive in the class scope, but trying to refer to it as if it's defined in local scope. You need to prefix it with self or SimpleEcho.

class SimpleEcho(WebSocket):
    progressive = Progressive()

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

Same issue with your Progressive class. Note that affect should be defined with an initial self argument, as it's not a staticmethod:

class Progressive():
    progressive = 0

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

HOWEVER!

What you're doing here means that every instance of Progressive will modify the same progressive attribute (and ditto every SimpleEcho instance). What you probably want to do is declare the progressive attribute on both classes when an instance is initialised:

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

Upvotes: 2

Related Questions