0

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

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>}
4

1 回答 1

3

在函数内部,vars()locals(). 因此不允许函数范围之外的函数。

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

于 2012-08-21T23:18:45.913 回答