can you use getattr to call a function within your scope?

孤街浪徒 提交于 2019-12-23 18:29:11

问题


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()

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?


回答1:


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

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

i.e

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

foo()

Output:

used getattr to call bar



回答2:


alternatively, you can also use the locals() function which returns a dict of local symbols:

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

foo()

It also allows you to get the function by its name instead of its reference without need for a custom mapping.



来源:https://stackoverflow.com/questions/52763125/can-you-use-getattr-to-call-a-function-within-your-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!