Simpler way to create dictionary of separate variables?

前端 未结 27 2358
名媛妹妹
名媛妹妹 2020-11-22 02:42

I would like to be able to get the name of a variable as a string but I don\'t know if Python has that much introspection capabilities. Something like:

>&         


        
27条回答
  •  别那么骄傲
    2020-11-22 03:17

    It will not return the name of variable but you can create dictionary from global variable easily.

    class CustomDict(dict):
        def __add__(self, other):
            return CustomDict({**self, **other})
    
    class GlobalBase(type):
        def __getattr__(cls, key):
            return CustomDict({key: globals()[key]})
    
        def __getitem__(cls, keys):
            return CustomDict({key: globals()[key] for key in keys})
    
    class G(metaclass=GlobalBase):
        pass
    
    x, y, z = 0, 1, 2
    
    print('method 1:', G['x', 'y', 'z']) # Outcome: method 1: {'x': 0, 'y': 1, 'z': 2}
    print('method 2:', G.x + G.y + G.z) # Outcome: method 2: {'x': 0, 'y': 1, 'z': 2}
    

提交回复
热议问题