当我尝试在函数中调用它时,为什么我不能使用vars()?

时间:2012-08-21 23:16:12

标签: python function built-in

我有一个字符串,这些字符串对应于函数名称。我正在尝试使用vars()将这些字符串分配给我可以用于函数调用的变量。我能够让vars()在函数之外工作,但是当我尝试在函数内调用它时,我得到一个KeyError。下面的代码显然不是我遇到的实际代码,但问题是一样的:我可以在vars()dict中找到密钥,但我不能从函数中调用它。

vars()正在工作:

In [1]: def brian():
   ...:     print "this is the brian function"
   ...:     

In [2]: name = 'brian'

In [3]: x = vars()[name]

In [4]: x()
this is the brian function

vars()无效(在函数内):

In [20]: def brian():
   ....:     print "this is the brian function"
   ....:     

In [21]: def run_it():
   ....:     name = 'brian'
   ....:     x = vars()[name]
   ....:     x() 
   ....:     

In [22]: run_it()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-22-15adf33a5fea> in <module>()
----> 1 run_it()

<ipython-input-21-5663ac30227d> in run_it()
      1 def run_it():
      2     name = 'brian'
----> 3     x = vars()[name]
      4     x()
      5 

KeyError: 'brian'

最后,这里是vars()( 包含关键'brian'):

In [4]: vars()
Out[4]: 
{'In': ['',
  u'def brian():\n    print "this is the brian function"\n    ',
  u"def run_it():\n    name = 'brian'\n    x = vars()[name]\n    x()\n    ",
  u'run_it()',
  u'vars()'],
 'Out': {},
 '_': '',
 '__': '',
 '___': '',
 '__builtin__': <module '__builtin__' (built-in)>,
 '__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__name__': '__main__',
 '_dh': [u'/Users/brian'],
 '_i': u'run_it()',
 '_i1': u'def brian():\n    print "this is the brian function"\n    ',
 '_i2': u"def run_it():\n    name = 'brian'\n    x = vars()[name]\n    x()\n    ",
 '_i3': u'run_it()',
 '_i4': u'vars()',
 '_ih': ['',
  u'def brian():\n    print "this is the brian function"\n    ',
  u"def run_it():\n    name = 'brian'\n    x = vars()[name]\n    x()\n    ",
  u'run_it()',
  u'vars()'],
 '_ii': u"def run_it():\n    name = 'brian'\n    x = vars()[name]\n    x()\n    ",
 '_iii': u'def brian():\n    print "this is the brian function"\n    ',
 '_oh': {},
 '_sh': <module 'IPython.core.shadowns' from '/Library/Frameworks/Python.framework/Versions    
/2.7/lib/python2.7/site-packages/IPython/core/shadowns.pyc'>,
 'brian': <function __main__.brian>,
 'exit': <IPython.core.autocall.ExitAutocall at 0x1598cb0>,
 'get_ipython': <bound method TerminalInteractiveShell.get_ipython of     
<IPython.frontend.terminal.interactiveshell.TerminalInteractiveShell object at 0x1589f70>>,
 'help': Type help() for interactive help, or help(object) for help about object.,
 'quit': <IPython.core.autocall.ExitAutocall at 0x1598cb0>,
 'run_it': <function __main__.run_it>}

1 个答案:

答案 0 :(得分:3)

在函数内部,vars()locals()相同。因此,不允许在函数范围之外使用函数。

您可能希望使用globals()vars()外部函数的行为)