Consider the following class:
class Token:
def __init__(self):
self.d_dict = {}
def __setattr__(self, s_name, value):
self.d_dict[s_name] = value
def __getattr__(self, s_name):
if s_name in self.d_dict.keys():
return self.d_dict[s_name]
else:
raise AttributeError('No attribute {0} found !'.format(s_name))
There is another function in my Token code (e.g. get_all () that returns d_dict has (s_name) that tell me if my token has a specific attribute).
In any case, I think this is a flaw in my plan, because it does not work: when I create a new instance, the python tries to call __setattr__('d_dict', '{}').
How can I achieve similar behavior (perhaps in a more pythonic way?) Without having to write something like Token.set (name, value) and get (name), each of which I want to set or get an attribute for the token.
Critics about the lack of design and / or stupidity are welcome :)
Thanks!
source
share