I have the following class:
class vehicle(object):
def __init__(self, name):
self.name = name
self.kinds_list = ["tank", "car", "motorbike", "bike", "quad" ]
@property
def kind(self):
return self.kind
@kind.setter
def kind(self, x):
if x in self.kinds_list:
self.kind = x
else:
raise AttributeError('No attribute {0} found !'.format(y))
Setting kind causes the maximum recursion depth exceeded aka stack overflow.
Q: How to re-write the setter to make it work with fixed list only?
The reason you reached the maximum recursion depth is that inside your setter, you do
self.kind = ...
, which recursively calls the same setter. You should store the value as some private attribute, just renameself.kind
toself._kind
.This is not a real private attribute like in other languages, since nothing prevents you from accessing
my_vehicle._kind
. By convention in python, everything starting with an underscore is private and shouldn't normally be touched outside of the class. Or as they say: python is for consenting adults ;).I also slightly modified the error message in the setter.