在教程中,我看到了两种用于使用 @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 类的行为,因为 @x.setter 似乎立即在 __init__ 中使用,但是这段代码在 PyCharm 中给了我一个警告(我将其作为注释)。如果这是 Python 属性设置器的正确使用,为什么会出现警告? B 类中没有警告。我能以某种方式在 __init__ 中调用 @x.setter 吗?就像在 A 类中一样,没有警告吗?
这似乎是 PyCharm 中的一个错误:https://youtrack.jetbrains.com/issue/PY-25263 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)