Python USES the dot operator to access the dictionary of dict data

  • 2020-04-02 14:41:25
  • OfStack

This article illustrates how python USES the point operator to access dictionary (dict) data. Share with you for your reference. Specific analysis is as follows:

Dict ['name'] is usually used to access dictionaries in a way similar to dict['name']. It would be more convenient to access dictionaries by dict.name. The following code defines a custom class to provide this method.


class DottableDict(dict):
  def __init__(self, *args, **kwargs):
    dict.__init__(self, *args, **kwargs)
    self.__dict__ = self
  def allowDotting(self, state=True):
    if state:
      self.__dict__ = self
    else:
      self.__dict__ = dict()
d = DottableDict()
d.allowDotting()
d.foo = 'bar'
print(d['foo'])
# bar
print(d.foo)
# bar
d.allowDotting(state=False)
print(d['foo'])
# bar from //www.jb51.net
print(d.foo)
# AttributeError: 'DottableDict' object has no attribute 'foo'

I hope this article has helped you with your Python programming.


Related articles: