Set self._a
, not self.a
; the latter uses the property setter:
class Abc(object):
def __init__(self, a=None):
self._a = a
or use a numeric default instead:
class Abc(object):
def __init__(self, a=0):
self.a = a
Question
I'm using properties in order to get/set variables in my class, but when the variable is set to None, the program crashes the next time the variable is set - like in the following code:
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
When I run this I get:
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'
What's the correct way of writing the code to stop this error occurring?
Solution
Set self._a
, not self.a
; the latter uses the property setter:
class Abc(object):
def __init__(self, a=None):
self._a = a
or use a numeric default instead:
class Abc(object):
def __init__(self, a=0):
self.a = a