I understand the concept of getter/setter in python. The thing I am not able to understand is, I need to add new value to the variable itself and I am not sure how I can achieve this with @property decorator.
The old code instantiates some variables and self increment them. I am trying to refactor the code and move those variables to a class and add @property/setter so that I can access them as attributes.
Old Code:
class ExistingCode(object):
a = 0
b = 0
c = 0
d = 0
bunch of other code..
a += 12
b += 12
c += 12
d += 12
What I am trying to do is:
class Variables(object):
def __init__(self):
a = 0
b = 0
c = 0
d = 0
@property
def a(self):
return self.a
@a.setter
def a(self, x)
a = x
......
I am getting "RuntimeError: maximum recursion depth exceeded". Please help.
I found the issue. The main problem was that I was using the same name for the attribute and the property as mentioned by @martineau. Also, I missed self in many places. Below is the working example.
class Variables(object):
def __init__(self):
self.a = 0
@property
def a(self):
return self.__a
@a.setter
def a(self, x):
self.__a = x
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.