Using Python to create a dictionary with setters and getters -
i have class method create dictionary. set , these values this:
class test(object): def __init__(self): self.config = {} def set_config_key(self, key, value): self.config[key] = value def _get_config_value(self, key): homecoming self.config[key]
in python 2.7 there improve way of doing this?
yes, can utilize attribute access the __getattr__
, __setattr__
methods instead:
class test(object): config = none def __init__(self): self.config = {} def __setattr__(self, key, value): if self.config none: # set config straight super(test, self).__setattr__(key, value) homecoming self.config[key] = value def __getattr__(self, key): homecoming self.config[key]
this translates test().foo
test().config['foo']
.
demo:
>>> t = test() >>> t.foo = 'bar' >>> t.foo 'bar' >>> t.config {'foo': 'bar'}
you map straight object __dict__
, instead of self.config
; if subclass dict
object both mapping , takes arbitrary attributes:
class attrdict(dict): def __init__(self, *args, **kw): super(attrdict, self).__init__(*args, **kw) self.__dict__ = self
demo:
>>> class attrdict(dict): ... def __init__(self, *args, **kw): ... super(attrdict, self).__init__(*args, **kw) ... self.__dict__ = self ... >>> foo = attrdict() >>> foo.bar = 'baz' >>> foo {'bar': 'baz'} >>> foo.bar 'baz'
python
No comments:
Post a Comment