Skip to main content
 首页 » 编程设计

python之为什么 PyCharm 在此处使用 @property 时会发出警告

2025年02月15日7sxdcgaq8080

在教程中,我看到了两种为了使用@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 的属性 setter ,为什么会出现警告? B 类中没有警告。我能以某种方式在 __init__ 中以与 A 类中相同的方式在没有警告的情况下调用 @x.setter 吗?

请您参考如下方法:

这似乎是 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