您可以使用getattr来调用您范围内的函数吗? [英] can you use getattr to call a function within your scope?

查看:97
本文介绍了您可以使用getattr来调用您范围内的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行类似的操作,但是我不知道如何调用函数bar.

I'm trying to do something like this, but I can't figure out how to call the function bar.

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

foo()

注意,这有点不寻常.通常,您将拥有一个对象并在该对象上获得一个属性,该属性可以是一个函数.那么它很容易运行.但是,如果您仅在当前作用域内有一个功能,该怎么办?如何在当前作用域内执行getattr来运行该功能?

Notice, that this is somewhat unusual. Normally you'd have an object and get an attribute on that, which could be a function. then it's easy to run. but what if you just have a function within the current scope - how to do getattr on the current scope to run the function?

推荐答案

您很亲密.要使用getattr,请传递名称的字符串值属性:

You are close. To use getattr, pass the string value of the name of the attribute:

getattr(bar, "__call__")('bar')

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

foo()

输出:

used getattr to call bar

这篇关于您可以使用getattr来调用您范围内的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆