Python: Using vars() to assign a string to a variable

前端 未结 6 1877
南笙
南笙 2020-11-27 17:09

I find it very useful to be able to create new variables during runtime and create a dictionary of the results for processing later, i.e. writing to a file:

         


        
6条回答
  •  温柔的废话
    2020-11-27 17:41

    jcdyer explains the concepts very well and Justin Peel clearly states what vars() and locals() do. But a small example always speeds up understanding.

    class Bull(object):
    
        def __init__(self):
            self.x = 1
            self.y = "this"
    
        def __repr__(self):
            return "Bull()"
    
        def test1(self):
            z = 5
            return vars()
    
        def test2(self):
            y = "that"
            return vars(self)
    
        def test3(self):
            return locals()
    
        def test4(self):
            y = 1
            return locals()
    
    if __name__ == "__main__":
        b = Bull()
        print b.test1()
        print b.test2()
        print b.test3()
        print b.test4()
        print vars(b).get("y")
    

    Which results in:

    {'self': Bull(), 'z': 5}
    {'y': 'this', 'x': 1}
    {'self': Bull()}
    {'y': 1, 'self': Bull()}
    this
    

提交回复
热议问题