List of class method not autocompleting in PyCharm

a 夏天 提交于 2020-02-05 03:21:12

问题


I am new to python and I have a question about autocompletion of method calls on an object within a list using Pycharm.

I have a class called foo():

class foo(object):

    def __init__(self):
        self.num = 10


    def getNum(self):
        return self.num

I then create a list called myList and append a foo() object to it. For some reason when I go to try and call the object the method doesn't show up.

However, if I complete the code with print(myList[0].getNum()), it will indeed print out 10.

Also, if I simply create a variable x and assign it to a foo() object, it will show up just fine like so:

I tried to create a y variable and assign it to myList[0] to see if I can get the method to show up, but still no luck.

Is this just an IDE issue or is there a bigger picture that I am missing when doing method calls working with objects inside of list.


回答1:


The reason is that python has dynamic typing. There is no constraint that myList must contain ONLY foo objects. So PyCharm can't know that myList[0] is a foo to give you the autocomplete for foo (that's only known at runtime).

Take this example:

class foo(object):

    def __init__(self):
        self.num = 10


    def getNum(self):
        return self.num

class bar(object):

    def __init__(self):
        self.num = 10


    def getNum2(self):
        return self.num

myList = []
myList.append(foo())
myList.append(bar())
print(myList[0])

PyCharm doesn't know whether to give you the autocomplete for foo() or bar() so it doesn't give you either.

The last case regarding x works because you explicitly assigned x as a foo object, so Pycharm knows and gives you the autocomplete for foo.




回答2:


Im pretty sure this is an IDE issue as it may not trace the variable all the way back to its original calls until actually ran. so with you setting x directly to foo() was one assignment but setting y = myList[0] and then getting the object at myList[0] which would be another call back to the variable if that makes sense.




回答3:


From python 3.5, you can use typing which provides advanced typing feature that pyCharm can use to suggest autocompletion.

see https://stackoverflow.com/a/59971921/2696355 for an example and the typing doc for more information



来源:https://stackoverflow.com/questions/43835786/list-of-class-method-not-autocompleting-in-pycharm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!