Pycharm visual warning about unresolved attribute

2020-08-09 12:07发布

问题:

I have two classes that look like this:

class BaseClass(object):

    def the_dct(self):
        return self.THE_DCT


class Kid(BaseClass):

    THE_DCT = {'vars': 'values'}


# Code i ll be running
inst = Kid()
print(inst.the_dct)

Inheritance has to be this way; second class containing THE_DCT and first class containing def the_dct.

It works just fine, but my problem is that i get a warning in Pycharm (unresolved attribute reference), about THE_DCT in BaseClass.

  • Is there a reason why it's warning me (as in why i should avoid it)?
  • Is there something i should do differently?

回答1:

Within BaseClass you reference self.THE_DCT, yet when PyCharm looks at this class, it sees that THE_DCT doesn't exist.

Assuming you are treating this as an Abstract Class, PyCharm doesn't know that that is your intention. All it sees is a class accessing an attribute, which doesn't exist, and therefore it displays the warning.

Although your code will run perfectly fine (as long as you never instantiate BaseClass), you should really change it to:

class BaseClass(object):
    THE_DCT = {}

    def the_dct(self):
        return self.THE_DCT