为什么在此处使用@属性 时PyCharm 会发出警告?
Why does PyCharm raise a warning when using @property here?
在教程中我看到了两种为了使用@属性而命名的实例属性。这是显示两者示例的代码。它们的工作方式似乎也不同。
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
我更喜欢 class 的行为,因为它似乎在 __init__ 中立即使用了 @x.setter,但是那段代码在 [=] 中给了我一个警告25=](我把它作为评论)。如果正确使用 Python 的 属性 setter,为什么会有警告? class B 中没有警告。我可以在 __init__ 中以与 class 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
在教程中我看到了两种为了使用@属性而命名的实例属性。这是显示两者示例的代码。它们的工作方式似乎也不同。
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
我更喜欢 class 的行为,因为它似乎在 __init__ 中立即使用了 @x.setter,但是那段代码在 [=] 中给了我一个警告25=](我把它作为评论)。如果正确使用 Python 的 属性 setter,为什么会有警告? class B 中没有警告。我可以在 __init__ 中以与 class 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