【问题标题】:Python define function within function [closed]Python在函数中定义函数[关闭]
【发布时间】:2019-08-18 19:13:22
【问题描述】:

我想在函数中定义一个函数,并从函数外调用它。这是我的代码的简化版本:

def make_func():
    exec('def test(text):\n\tprint(text)')


make_func()
test("Hello")

当我运行这段代码时,我得到了这个错误:

Traceback (most recent call last):
line 6, in <module>
    test("Hello")
NameError: name 'test' is not defined

提前感谢您的帮助。

【问题讨论】:

  • 您为什么要这样做?我认为 test 只在 exec 的范围内定义
  • 您对我可以使用的其他功能有什么建议吗?
  • 有什么意义?您要达到什么目的,而您无法通过正常方式定义功能来实现? (你为什么把exec 带进来?)
  • 这是我实际代码的简化版本,我必须在函数中动态创建一个函数。我不需要使用exec(),但我想不出另一种方法来做到这一点

标签: python function


【解决方案1】:

修订:

您需要将 test 添加到全局名称中。这是解决方案:

def make_func():
    exec('def test(text):\n\tprint(text)', globals())


make_func()
test("Hello")

注意: 这是asked before


上一个:

Python exec()。你不能调用 text("Hello) 因为 text() 已经超出范围并且不再被定义。它只在 exec() 的范围内定义。

但是,您可以这样做:

def make_func():
    exec('def test(text):\n\tprint(text)\ntest("Hello")')


make_func()

或者:

def make_func(text):
    exec('def test(text):\n\tprint(text)\ntest(text)')


make_func("Hello")

希望对您有所帮助。

【讨论】:

  • 我希望从exec() 语句之外调用该函数,但感谢您的建议
  • 我是说,这是不可能的。 exec() 中定义的函数仅在 exec() 范围内可用。见链接。
  • 我可以使用其他函数来代替exec()吗?
  • 我无法想象有,但我不知道。我认为这不太可能。
  • 这是不对的。 exec 内部定义的名称可以在其外部使用。
【解决方案2】:

test 函数在 make_func 函数内部定义,因此是它的本地函数,以使其全局(可从代码中的任何位置访问)使用(对于 Python 2.7):

def make_func():
    exec('def test(text):\n\tprint(text)')
    globals()['test'] = test

make_func()
test("Hello")  #  ==>  Hello

对于 Python 3.x:

def make_func():
    exec('def test(text):\n\tprint(text)', globals())

make_func()
test("Hello")  #  ==>  Hello

【讨论】:

  • 我刚刚收到这个错误:line 3, in make_func globals()['test'] = test NameError: name 'test' is not defined
  • @Pokechu48 它适用于 Python 2.7,我将看到 Python 3.x 的解决方法。
  • @Pokechu48 检查编辑以获取 Python 3.x 的解决方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多