skip to Main Content

With the following code, vscode doesn’t seems to recognize the last method, bot.server.test_method() although implemented in the server class.
running result works find, but only vscode not highlight the bot.server.test_method() as existing method.

Anyone knows, how to make vscode recognize the bot.server.test_method()?

class mybot():
    def __init__(self, server=None):
        self.server = server

    def test_method(self):
        print('hello bot a')

class myserver():    
    def test_method(self):
        print('hello server a')

if __name__ == '__main__':
    bot = mybot(myserver())
    bot.test_method()
    bot.server.test_method()

--result--
class_test.py
hello bot a
hello server a

2

Answers


  1. The problem of not recognizing bot.server.test_method() is related to the way the bot variable was named. You have defined a class called bot and also created an instance with the same name bot. This can be confusing because the bot variable is shadowing the bot class.

    Login or Signup to reply.
  2. The core of the issue is that the mybot.server variable has no type hint associated with it in the class, so your editor does not ‘know’ what the type of server should be once it is ‘inside’ your bot class.

    The easiest way to fix this is to just add type hints, yielding:

    class myserver():
        def __init__(self):
            pass
    
        def test_method(self):
            print('hello server a')
    
    class mybot():
        def __init__(self, server : myserver=None):
            self.server = server
    
        def test_method(self):
            print('hello bot a')
    
    if __name__ == '__main__':
        bot = mybot(myserver())
        bot.test_method()
        bot.server.test_method()
    

    Where the key line is def __init__(self, server : myserver=None):
    The type hint : myserver for the server parameter tells your editor that the parameter will be of your server type.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search