Simpler way to create dictionary of separate variables?

前端 未结 27 1918
名媛妹妹
名媛妹妹 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:24

    With python 2.7 and newer there is also dictionary comprehension which makes it a bit shorter. If possible I would use getattr instead eval (eval is evil) like in the top answer. Self can be any object which has the context your a looking at. It can be an object or locals=locals() etc.

    {name: getattr(self, name) for name in ['some', 'vars', 'here]}
    

提交回复
热议问题