PyCharm f-string usage in a class displays warning (Unresolved attribute reference '__name' for class...)

python pycharm

632 观看


1 作者的声誉

(short version of code)

class Animal:
    __name = ""
    __gender = "unknown"
    __height = 0
    __weight = 0
    __hungry = False

    def __init__(self, name, gender, height, weight):
        self.__name, self.__gender, self.__height, self.__weight = name, gender, height, weight

    def toString(self):
        return f'{self.__name} is a {self.__gender}, {self.__height} m tall and weights {self.__weight} kg.'

PyCharm warns me: Unresolved attribute reference '__name' for class 'Animal'

The code is still working as intended. Why does this warning pop up?

f-strings seem a cleaner version of str.format for me and they are also faster. PS. As I'm a newbie to Python, please feel free to bring out all the stylish errors or what could and should be done better :)

Python version: 3.6.4 PyCharm Community version: 2017.3.1

Picture of the code and the error

作者: Estonian 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


621 作者的声誉

There is this post from about a year ago and also this. It seems like it could be an issue with PyCharm.

However, if you remove the double underscores within the f string, the linter no longer complains.

Calling ''.format() with the dunder prefixed attribute seems to not produce errors or warnings either.

As @kindall stated above prefixing with the double underscore invokes name mangling.

class Animal:
    __X = 'y'

    def __init__(self, name="", gender="", height=0, weight=0, hungry=False): = name
        self.gender = gender 
        self.height = height
        self.weight = weight
        self.hungry = hungry

    def to_string(self):
        return f'{} is a {self.gender}, {self.height} m tall and weights {self.weight} kg.'

    def to_string_format(self):
        return '{}'.format(self.__X)

Also they seem to know about bugs pertaining to this issue. I would bring it up; it would be good for them to get some more information.

作者: eric 发布者: 27.12.2017 07:20