属性setter上的@property装饰器

时间:2014-09-30 11:51:53

标签: python

以下代码引发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

1 个答案:

答案 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