代码之家  ›  专栏  ›  技术社区  ›  damir

从字符串定义变量

  •  4
  • damir  · 技术社区  · 16 年前

    我试图在函数中定义变量。vars()显示变量已创建,但给出了NameError:exception。我做错什么了?

    def a(str1):
        vars() [str1] =  1
        print vars()
        print b
    
    
    a('b')
    

    输出:

    {'str1': 'b', 'b': 1}
    

    例外情况:

    NameError: global name 'b' is not defined
    
    3 回复  |  直到 16 年前
        1
  •  2
  •   Donald Miner    16 年前

    你的代码对我有用。或许你应该尝试另一种方法:

    exec(str1 + '=1')
    

    b=1

        2
  •  4
  •   Thomas    16 年前

    你在调用未定义的行为。从 documentation of vars() :

    注意 不应修改返回的字典:对相应符号表的影响未定义。

    其他答案给出了可能的解决方案。

        3
  •  1
  •   msw    16 年前

    如果你不明白一个构造为什么不能工作,那么下一个必须阅读你代码的人也不会理解。如果你是说

    b = 1   
    

    你应该这么说。在这种情况下 vars() 允许您访问函数本地字典,以便您的代码与

    def a():
       b = 1
    

    b 是本地的 a 一

    过早的优化是许多人试图猜测Python的根源

    from itertools import izip
    import timeit
    
    import msw.wordlist
    
    def zip_list(p):
        """construct a dictionary of length 100 from a list of strings"""
        return dict(zip(p[:100], p[100:]))
    
    def izip_list(p):
        """as zip_list but avoids creating a new list to feed to dict()"""
        return dict(izip(p[:100], p[100:]))
    
    def pass_list(p):
        """take 100 elements of a list and do nothing"""
        for i in p[:100]:
            pass
    
    def exec_pass_list(p):
        """exec() a no-op 100 times"""
        for i in xrange(100):
            exec('pass')
    
    
    # returns a list of 64'000 unique lowercase dictionary words for tests
    words = msw.wordlist.Wordlist()
    words.shuffle()
    words = words[:200]
    print 'words', words[:5], '...'
    
    for func in ['zip_list', 'izip_list', 'pass_list', 'exec_pass_list']:
        t = timeit.Timer('%s(words)' % func,
                'from __main__ import words, %s' % func)
        print func, t.repeat(number=10**5)
    

    由此产生:

    words ['concatenated', 'predicament', 'shtick', 'imagine', 'stationing'] ...
    zip_list [1.8603439331054688, 1.8597819805145264, 1.8571949005126953]
    izip_list [1.5500969886779785, 1.5501470565795898, 1.5536530017852783]
    pass_list [0.26778006553649902, 0.26837801933288574, 0.26767921447753906]
    exec_pass_list [74.459679126739502, 75.221366882324219, 77.538936853408813]