Python:使用字符串调用子函数



是否有人知道如何使用点运算符调用属于父函数的子函数,但子函数的名称存储在字符串变量中。

def parent_function():
# do something
def child_function():
# do something else

现在假设我有一个名为"child_function"的字符串。有没有办法做到这一点:

method_name = 'child_function'
parent_function.method_name()

我知道method_name是一个字符串,因此它是不可调用的。上面的语法显然是错误的,但我想知道是否有办法做到这一点?

谢谢!

正如其他人在评论中指出的那样,实际调用内部函数需要更多的设置,比如这样的参数:

def parent_function(should_call=False):
# do something
def child_function():
print("I'm the child")
if should_call:
child_function()

话虽如此,为了回答您的具体问题,您可以直接调用内部函数。我应该注意到这很糟糕,你应该而不是这样做。您可以通过外部函数的代码对象访问内部函数

exec(parent_function.__code__.co_consts[1])

与许多注释相反,即使外部函数不再在系统内存中,您也可以访问内部函数。python中的这种技术被称为闭包。要了解更多关于关闭的信息,请访问Programiz

根据您的需求,您需要在嵌套函数之外调用嵌套方法。

我们在利用什么?

  1. python的闭包技术
  2. locals()方法,它返回封闭方法内部的所有局部属性和方法
  3. lambda x: x,一个匿名(Lambda)函数
def parent_function():
# do something
def child_function():
# do something else
print("child_function got invoked")
return {i: j for i, j in locals().items() if type(j) == type(lambda x: x)}
# locals() returns all the properties and nested methods inside an enclosing method.
# We are filtering out only the methods / funtions and not properties / variables
parent_function()["child_function"]()

以下是输出。

>>> child_function got invoked

更好的解决方案:

不要使用嵌套方法,而是利用Python提供的类的概念。将嵌套函数作为方法封装在类中。

如果在parent_function中包含global child_function,那么一旦运行parent_function,就可以在主程序中调用child_function。不过,这并不是一种定义函数的干净方法。如果你想在主程序中定义一个函数,那么你应该在主程序中将其定义。

考虑以下情况:

def parent_function():
a = 1

您可以从全局范围访问a吗?不,因为它是一个局部变量。它只在parent_function运行时存在,之后就被遗忘了。

现在,在python中,函数和其他值一样存储在变量中。child_functiona一样是一个局部变量。因此,原则上不可能从parent_function外部访问它。

编辑:除非你以某种方式让它对外部可用,例如通过返回它。但是,名称child_function仍然是parent_function的内部名称。

编辑2:您可以使用locals()globals()字典获得按名称(字符串)给定的函数。

def my_function():
print "my function!"
func_name = "my_function"
f = globals()[func_name]
f()

最新更新