1

In Python,

Is there a way to access dict similar the way a method is invoked on an object. Scenario is, I thought to create a class with just attributes, there are no methods. And I came across few discussion on this scenario Python: Should I use a class or dictionary?. I've decided to go for dict instead of class.

No I would just like to understand, is there a way I can access elements of dict similar to method invocation on a object?

mydict = {'a': 100, 'b': 20.5, 'c': 'Hello'}

Instead of,

mydict['a']
mydict['a'] = 200

Something like,

mydict.a
mydict.a = 200

namedtuple does solve one part, that is, I can initialize and read. But not to be intended to set/write values.

Andy G
  • 19,232
  • 5
  • 47
  • 69

1 Answers1

3

This is easily done by implementing __getattr__ and __setattr__ in a subclass:

class MyDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value
L3viathan
  • 26,748
  • 2
  • 58
  • 81
  • @PaulPanzer Well yes. You _could_ get around that (with `__getattribute__`), but I don't think it's worth the effort. – L3viathan Dec 14 '17 at 13:35