这个python工厂函数是如何工作的

2024-05-16 17:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的pluralsight python类中的python函数:

def raise_to(exp):
    def raise_to_exp(x):
        return pow(x, exp)
    return raise_to_exp

现在,讲师将打开一个交互式会话,并执行以下操作:

  • 从raise_导入raise_到
  • square=将_提高到(2),然后继续执行
  • 广场(5)

结果是25。如何或为什么传入两个不同的参数?现在我对这段代码进行了调试,这就是我观察到的。当我这样做时:

def raise_to(exp):
    def raise_to_exp(x):
        return pow(x, exp)
    return raise_to_exp

square = raise_to(2)

print(square)

我得到:<function raise_to.<locals>.raise_to_exp at 0x00000246D1A88700>,但如果我像讲师那样做

def raise_to(exp):
    def raise_to_exp(x):
        return pow(x, exp)
    return raise_to_exp

square = raise_to(2)

print(square(5))

我得到25分。我想知道这是怎么回事。我知道这被称为python工厂函数,但它是如何工作的。函数是否存储了第一个参数,以便以后与传入的第二个参数一起使用


Tags: to函数代码参数returndeffunctionraise
2条回答

raise_to_exp是由raise_to定义的参数exp上的闭包。调用raise_to(2)时,返回一个函数,在该函数体中,变量exp引用了定义raise_to_exp的作用域中的变量

这意味着square是一个函数,其中exp绑定到2,因此大致相当于定义

def square(x):
    return pow(x, 2)

为了证明没有用值2替换exp,您可以深入function对象来更改exp的值

>>> square(5)
25
>>> square.__closure__[0].cell_contents = 3  # now square is cube!
>>> square(5)
125

def raise_to(exp):
    def raise_to_exp(x):
        return pow(x, exp)
    return raise_to_exp

我最后的发言很大胆。你在这里返回一个函数。把它想象成

a=lambda x:x+1
a(1)
# 2

当你这样做的时候

square=raise_to(2)

现在square引用函数raise_to_exp,因为raise_to返回了raise_to_exp函数square可以在这里用作函数

square(2) # with exp set as 2
# 4

cube=raise_to(3)
cube(2)
# 8

相关问题 更多 >