以下代码引发AttributeError: can't set attribute
错误:
# code_1
class Pair(object):
def __init__(self):
self._k1 = 0
self._k2 = 0
@property
def k1(self, k1):
self._k1 = k1
@property
def k2(self, k2):
self._k2 = k2
@k1.getter
def k1(self):
return self._k1
@k2.getter
def k2(self):
return self._k2
>>> p=Pair()
>>> p.k1 = 10
>>> AttributeError: can't set attribute
似乎p.k1
分配导致错误。但是,用@property
装饰吸气剂是完美的。查看以下可正常工作的代码:
# code_2
class Pair(object):
def __init__(self):
self._k1 = 0
self._k2 = 0
@property
def k1(self):
return self._k1
@property
def k2(self):
return self._k2
@k1.setter
def k1(self, k1):
self._k1 = k1
@k2.setter
def k2(self, k2):
self._k2 = k2
知道为什么code_1
抛出AttributeError
?
答案 0 :(得分:1)
您只需要@property
来获取变量,setter
来设置变量。
class Pair(object):
def __init__(self):
self._k1 = 0
self._k2 = 0
@property # set the value k1
def k1(self):
return self._k1
@property # set the value k2
def k2(self):
return self._k2
@k1.setter # use the setter
def k1(self, value):
self._k1 = value
@k2.setter # use the setter
def k2(self, value):
self._k2 = value
请注意,@getter
是多余的,因为@property
隐式为getter
。然后,您需要定义@k1.setter
来设置值。
有关更多信息,请参阅comment below by Lukas Graf。
>>> p=Pair()
>>> p.k1=19
>>> print p.k1
19