0

文字列の辞書があり、それらの文字列は関数名に対応しています。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>}
4

1 に答える 1

3

関数内でvars()は、 と同じlocals()です。したがって、関数スコープ外の関数は許可されません。

使用したい場合がありますglobals()vars()外部関数の動作)

于 2012-08-21T23:18:45.913 に答える