为什么PyCharm在这里使用@property时会发出警告?

时间:2017-08-17 21:32:14

标签: python class properties pycharm naming

在教程中,我看到了两种类型的实例属性命名,目的是使用@property。以下是显示两者示例的代码。他们似乎也有不同的工作方式。

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

我更喜欢A类的行为,因为似乎@_init__中会立即使用@ x.setter,但是这段代码在PyCharm中给了我一个警告(我把它作为注释)。如果正确使用Python的属性设置器,为什么会出现警告?在B级中没有警告。我可以在__init__中以与A类相同的方式调用@ x.setter而不发出警告吗?

1 个答案:

答案 0 :(得分:1)

这似乎是PyCharm中的一个错误:https://youtrack.jetbrains.com/issue/PY-25263

我发现的一个临时解决方案是在__init__中添加self._x = None。所以代码是:

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