繁体   English   中英

无法理解 Python 嵌套函数

[英]Unable to understand Python nested function

我想弄清楚,这段代码如何在不调用函数(num2)的情况下工作?

例子:

def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))

输出:50

它确实调用了num2 这就是分配给res ,因此res(5)调用它。

如果您重写num1以使用 lambda 表达式可能会稍微清晰一些(这是可能的,因为定义和返回的函数的性质很简单):

def num1(x):
    return lambda y: x * y

res = num1(10)  # res is a function that multiplies its argument by 10
print(res(5))

如果您尝试在不提供任何参数的情况下打印 res,您会看到它的行为就像一个简单地指向函数地址的函数;

def num1(x):
   def num2(y):
      return x * y
   return num2

res = num1(10)

print(res)
print(res(5))

输出;

<function num1.<locals>.num2 at 0x02DDBE38>
50

我对此进行了评论以解释功能。

# Defined function named num1 taking input 'x'
def num1(x):
    # Function 'num2' defined inside 'num1' taking input 'y'
   def num2(y):
    # Second function returning num1 input * num2 input
      return x * y
    # First function returning num2 is returned first
   return num2
# this is a variable for inputting to the nested functions.
# res = num1(num2)
res = num1(10)
# This is initializing num1 as 5
print(res(5))


# But it would be way easier...
def nums(x,y):
    return x * y

print(nums(5,10))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM