You want __getattr__and __setattr__, although you have to roll your own class (I do not know any built-in functions, although it namedtuplecan work if you do not need to change the values much)
class AttrDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
If you just want to access the dictionary sub-languages, just change selftoself.cool_dict
class CoolThing:
def __init__(self):
self.cool_dict = {'a': 1, 'b': 2}
def __getattr__(self, attr):
return self.cool_dict[attr]
def __setattr__(self, attr, value):
if attr == 'cool_dict':
super().__setattr__(attr, value)
else:
self.cool_dict[attr] = value
, __getattr__ , , , __getattribute__
, self.cool_dict CoolThing , __init__. , , , self.cool_dict init, __setattr__, self.cool_dict, [attr] = value . , cool_dict, __getattr__..., cool_dict .
- , , , , :)
source
share