【问题标题】:Python: calling a child function using a stringPython:使用字符串调用子函数
【发布时间】:2021-11-17 09:56:10
【问题描述】:

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

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

现在想象我有一个名为“child_function”的字符串。有没有办法做到这一点:

method_name = 'child_function'
parent_function.method_name()

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

谢谢!

【问题讨论】:

  • 这不是一个正确的设计。您可以设置一个字典来进行映射:mapping = {'child_function': child_function, 'other_function': other_function}。这样一来,检查错误就很容易了。
  • 即使不是字符串,你怎么称呼它? child_functionparent_function 的本地地址。您无法从外部访问它。
  • 您必须设置一些逻辑,父级必须接受一个参数,其中每个值都将运行一个单独的子函数并在该参数上使用 if..else 返回一个值。
  • 最大的问题是“你为什么要这样做?”你想解决什么问题?这显然是XY Problem
  • 我同意其他人的观点。不要这样做。您要解决什么实际问题。

标签: python string methods parent-child


【解决方案1】:

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

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

【讨论】:

  • 感谢您的解释 - 了解了 code.co_consts[1] 的使用。
【解决方案2】:

与许多 cmets 不同,您实际上可以访问内部函数,即使外部函数不再位于系统内存中。 python中的这种技术称为闭包。 要了解更多关于关闭的信息,visit 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 提供的类的概念,而不是使用嵌套方法。 将嵌套函数作为方法封装在一个类中。

【讨论】:

    【解决方案3】:

    如果您在parent_function 中包含global child_function,那么一旦您运行parent_function,您就可以在主程序中调用child_function。不过,这不是一种非常简洁的函数定义方式。如果你想在主程序中定义一个函数,那么你应该在主程序中定义它。

    【讨论】:

      【解决方案4】:

      考虑以下情况:

      def parent_function():
        a = 1
      

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

      现在,在 python 中,函数存储在变量中,就像任何其他值一样。 child_function 是一个局部变量,就像 a 一样。因此,原则上无法从parent_function外部访问它。

      编辑:除非您以某种方式将其提供给外部,例如通过返回它。但是,child_function 的名称仍然是 parent_function 的内部名称。

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

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

      【讨论】:

        猜你喜欢
        • 2018-03-29
        • 2021-05-10
        • 2018-12-23
        • 2011-05-07
        • 2023-03-24
        • 2013-04-08
        • 1970-01-01
        • 2017-09-29
        相关资源
        最近更新 更多