Why does PyCharm raise a warning when using @property here?

风流意气都作罢 提交于 2020-01-04 05:27:18

问题


In tutorials I have seen two types of instance attribute naming for the purpose of using @property. Here is code showing examples of both. They also seem to work differently.

class A:
    def __init__(self, x):
        self.x = x

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, x):
        if x > 1000:
            self.__x = 1000
        else:
            self.__x = x  # Instance attribute __x defined outside __init__

class B:
    def __init__(self, x):
        self._x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        if x > 1000:
            self._x = 1000
        else:
            self._x = x

a = A(9999)
print(a.x)  # -> 1000

b = B(9999)  # -> 9999
print(b.x)
b.x = 9999
print(b.x)  # -> 1000

I like the behaviour of class A better as it seems that the @x.setter is used immediately in __init__, however that piece of code gives me a warning in PyCharm (I have it as a comment). Why would there be a warning if that is the proper use of a Python's property setter? There are no warnings in class B. Could I somehow call @x.setter in __init__ the same way as in class A without a warning?


回答1:


It seems to be a bug in PyCharm: https://youtrack.jetbrains.com/issue/PY-25263.

A temporary solution I found was to add self._x = None in the __init__. So the code would be:

class A:
    def __init__(self, x):
        self._x = None
        self.x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        if x > 1000:
            self._x = 1000
        else:
            self._x = x


a = A(9999)
print(a.x)  # -> 1000


来源:https://stackoverflow.com/questions/45745248/why-does-pycharm-raise-a-warning-when-using-property-here

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