如何在沒有pylint的情況下在__init__
中使用屬性設置器,抱怨該屬性已被定義在__init__
之外?在__init__中使用屬性設置器
例如,下面的代碼只會產生一個在底部try子句中捕獲的異常。
class CircleNotUsingSetterInInit(object):
def __init__(self, radius):
# Notice underscore in 'self.radius
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
if radius < 0:
raise ValueError("Radius must be non-negative")
self._radius = radius
class CircleUsingSetterInInit(object):
def __init__(self, radius):
# Notice lack of underscore in 'self.radius'
self.radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
if radius < 0:
raise ValueError("Radius must be non-negative")
# From pylint:
# Attribute '_radius' defined outside __init__ (attribute-defined-outside-init)
self._radius = radius
CircleNotUsingSetterInInit(5)
CircleNotUsingSetterInInit(-1)
CircleUsingSetterInInit(5)
try:
CircleUsingSetterInInit(-1)
except ValueError:
print("caught exception")
我正在使用Python 2.7.10。
'CircleUsingSetterInInit'是正確的行爲,您可以隨意忽略這個「pylint」,或者使用內聯註釋將其關閉。 – jonrsharpe