定义定义另一个函数的函数时出错
Error in defining a function that defines another function
(注意:-您可以滚动到粗体部分查看主要信息。)
感谢您花时间回答我的问题。我在定义一个函数时出现 python-3 错误,该函数定义另一个函数 ,代码如下:
def one():
def two():
print("two()")
one()
two()
错误:
Traceback (most recent call last):
File "C:\Users\homec\AppData\Local\Programs\Python\Python39\test.py", line 60, in <module>
two()
NameError: name 'two' is not defined
在定义了one()
之后,我调用了one()
所以我定义了two()
。然后 我调用了 two()
所以我打印了 "two()"
。那这里有什么问题呢,为什么说name 'two' is not defined
.
预先感谢您的回答。
您在函数 one
中定义了函数 two
,甚至没有 return。即使你 return 它,你也必须将 return 值存储在某个变量中,然后将该变量作为函数调用。试试这个代码:
def one():
def two():
print("Two")
return two
func = one()
func() #outputs 'Two'
two
函数在 outer/global 范围内不可用。
请参阅此示例,了解如何在全局范围内定义它:
In [7]: def one():
...: global two
...: def two():
...: print("two()")
...: one()
...: two()
two()
(注意:-您可以滚动到粗体部分查看主要信息。)
感谢您花时间回答我的问题。我在定义一个函数时出现 python-3 错误,该函数定义另一个函数 ,代码如下:
def one():
def two():
print("two()")
one()
two()
错误:
Traceback (most recent call last):
File "C:\Users\homec\AppData\Local\Programs\Python\Python39\test.py", line 60, in <module>
two()
NameError: name 'two' is not defined
在定义了one()
之后,我调用了one()
所以我定义了two()
。然后 我调用了 two()
所以我打印了 "two()"
。那这里有什么问题呢,为什么说name 'two' is not defined
.
预先感谢您的回答。
您在函数 one
中定义了函数 two
,甚至没有 return。即使你 return 它,你也必须将 return 值存储在某个变量中,然后将该变量作为函数调用。试试这个代码:
def one():
def two():
print("Two")
return two
func = one()
func() #outputs 'Two'
two
函数在 outer/global 范围内不可用。
请参阅此示例,了解如何在全局范围内定义它:
In [7]: def one():
...: global two
...: def two():
...: print("two()")
...: one()
...: two()
two()