Python makes dictionary items available as an object property

This is basically syntactic sugar, but I would like to access the dictionary elements as properties of the object.

Example:

class CoolThing():
  def __init__(self):
    self.CoolDict = {'a': 1, 'b': 2}

and i would like to have

my_cool_thing.a # => 1
my_cool_thing.b # => 2

Edit: some potential solution code with nested structure with dotted notation: device.property.field

class Parameters():

    def __init__(self, ids, devices):
        self._ids = ids
        self._devices = devices
        for p in self._devices:
            p = p[0]
            if self.__dict__.get(p.device) is None:
                self.__dict__[p.device] = SmartDict()
            else:
                if self.__dict__[p.device].get(p.property) is None:
                    self.__dict__[p.device][p.property] = SmartDict()
                else:
                    if self.__dict__[p.device][p.property].get(p.field) is None:
                        self.__dict__[p.device][p.property][p.field] = ParameterData(p)

class SmartDict():
    def __init__(self):
        self.__dict__ = {}

    def __getitem__(self, k):
        return self.__dict__[k]

    def __setitem__(self, k, v):
        self.__dict__[k] = v

    def get(self, k):
        return self.__dict__.get(k)

    def __len__(self):
        return len(self.__dict__)
+4
source share
2 answers

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):
      # Note, you'll have to do this for anything that you want to set
      # in __init__. 
      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 .

- , , , , :)

+5
source

CoolDictalready exists, it is called __dict__:

>>> class CoolThing(object):
...     def __init__(self):
...         self.__dict__['a'] = 1
...         self.__dict__['b'] = 2
... 
>>> thing = CoolThing()
>>> thing.a
1
>>> thing.b
2
>>> thing.c = 3
>>> thing.__dict__
{'a': 1, 'b': 2, 'c': 3}
+5
source

Source: https://habr.com/ru/post/1623447/


All Articles