我正在使用属性以便在我的类中获取/设置变量,但是当变量设置为None时,下一次设置变量时程序崩溃-就像下面的代码一样:
class Abc(object):
def __init__(self, a=None):
self.a = a
def set_a(self, value):
self._a = value*5
def get_a(self):
return self._a
a = property(get_a, set_a)
A = Abc()
A.a = 4
print A.a
当我运行这个时,我得到:
Traceback (most recent call last):
File "<string>", line 13, in <module>
File "<string>", line 3, in __init__
File "<string>", line 6, in set_a
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
如何写代码来阻止这个错误的发生?
Set self._a
, not self.a
;后者使用属性设置器:
class Abc(object):
def __init__(self, a=None):
self._a = a
或使用数字默认值:
class Abc(object):
def __init__(self, a=0):
self.a = a