Convert nested Python dict to object?

后端 未结 30 2593
时光取名叫无心
时光取名叫无心 2020-11-22 09:28

I\'m searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

30条回答
  •  一向
    一向 (楼主)
    2020-11-22 10:02

    class Struct(dict):
        def __getattr__(self, name):
            try:
                return self[name]
            except KeyError:
                raise AttributeError(name)
    
        def __setattr__(self, name, value):
            self[name] = value
    
        def copy(self):
            return Struct(dict.copy(self))
    

    Usage:

    points = Struct(x=1, y=2)
    # Changing
    points['x'] = 2
    points.y = 1
    # Accessing
    points['x'], points.x, points.get('x') # 2 2 2
    points['y'], points.y, points.get('y') # 1 1 1
    # Accessing inexistent keys/attrs 
    points['z'] # KeyError: z
    points.z # AttributeError: z
    # Copying
    points_copy = points.copy()
    points.x = 2
    points_copy.x # 1
    

提交回复
热议问题