0

I can't use self in a class.It seems that the data of the function after the decorator is the first parameter.

Example:

import socketio

import random

sio = socketio.Client()


class Test:
    def __init__(self):
        self.uid = random.randint(0, 10)

    @sio.on('test')
    def test(self, message):
        test_message = str(self.uid) + message
        print(test_message)

    @staticmethod
    def run():
        sio.connect('ws://127.0.0.1:5000')
        sio.wait()


if __name__ == '__main__':
    test = Test()
    test.run()

Error:

TypeError: test() missing 1 required positional argument: 'message'
ideasource
  • 11
  • 3
  • How can the socket.io package know what value `self` is supposed to have? Please expand your question indicating what is the expected behavior you wanted, then maybe I can give you advice on how to achieve it. – Miguel Grinberg Jan 26 '20 at 15:03

1 Answers1

1

By:miguelgrinberg

Right, so how is Socket.IO going to know that the value for self should be this test object you created near the bottom of the file? When you set up your handlers in this way there is really no link to the actual instance of the Test class.

Try setting the handlers once the class has been instantiated, maybe something like this:

def run(self):
    sio.on('test', self.test)
    sio.connect('ws://127.0.0.1:5000')
    sio.wait()
ideasource
  • 11
  • 3