Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 可以使用getattr调用范围内的函数吗?_Python_Getattr - Fatal编程技术网

Python 可以使用getattr调用范围内的函数吗?

Python 可以使用getattr调用范围内的函数吗?,python,getattr,Python,Getattr,我正在尝试这样做,但我不知道如何调用函数bar def foo(): def bar(baz): print('used getattr to call', baz) getattr(bar, __call__())('bar') foo() 注意,这有点不寻常。通常情况下,你会有一个对象,并得到一个属性,它可以是一个函数。那就很容易跑了。但是如果您只是在当前范围内有一个函数,该怎么办?如何在当前范围内执行getattr以运行该函数?您已经接近了。要使用get

我正在尝试这样做,但我不知道如何调用函数
bar

def foo():
    def bar(baz):
        print('used getattr to call', baz)
    getattr(bar, __call__())('bar')

foo()

注意,这有点不寻常。通常情况下,你会有一个对象,并得到一个属性,它可以是一个函数。那就很容易跑了。但是如果您只是在当前范围内有一个函数,该怎么办?如何在当前范围内执行getattr以运行该函数?

您已经接近了。要使用
getattr
,请传递属性的字符串值:

getattr(bar, "__call__")('bar')
i、 e

输出:

used getattr to call bar

或者,您也可以使用返回本地符号dict的函数:

def foo():
  def bar(baz):
    print('used getattr to call', baz)
  locals()['bar']('pouet')

foo()

它还允许您通过函数名而不是引用来获取函数,而无需自定义映射。

如果我想执行
getattr('bar',“\u调用”('bar')”)
?当我试图通过字符串引用函数时,我得到了
AttributeError:'str'对象没有属性'\uuuu call'
,有什么方法可以动态引用它的名称吗?我只是使用了一个映射,这是为了我的目的
methods={'bar':bar};getattr(方法['bar']…
只需调用
locals()
函数,它将从本地范围返回对象的字典
def foo():
  def bar(baz):
    print('used getattr to call', baz)
  locals()['bar']('pouet')

foo()