简体   繁体   English

将Lambda表达式转换为简单函数

[英]Transforming lambda expression to simple function

I'm curious if it is possible to avoid lambda expressions in the following case. 我很好奇在以下情况下是否有可能避免使用lambda表达式。

For example using lambda expression I can simple define a function that returns a lambda exp. 例如,使用lambda表达式,我可以简单地定义一个返回lambda exp的函数。

def square_fun(a,b,c):
   return lambda x: a*x**2 + b*x + c

After we can call it using: 之后我们可以使用以下命令调用它:

f = square_fun(1,2,3)

f(1) # here x = 1

How can I get the same behaviour avoiding lambda expression? 如何获得避免lambda表达式的相同行为?

for example, square_fun must return another function 例如,square_fun必须返回另一个函数

def square_fun(a,b,c):
   return f...

In python you can define a function inside another function, so the following snippet should give you the same behavior: 在python中,您可以在另一个函数中定义一个函数,因此以下代码段应具有相同的行为:

def square_fun(a, b, c):
    def result(x):
        return a*x**2 + b*x + c
    return result

f = square_fun(1, 2, 3)
print(f(1))
# Should print 6

So, I'll try to explain what's going on here: 因此,我将尝试解释这里发生的情况:

  1. In the line f = square_fun(1, 2, 3) , f will actually be mapped to the internal function (aka. result ) f = square_fun(1, 2, 3)f实际上将映射到内部函数(也称为result )。
  2. Please note that return result does not have the () at the end, hence the function is not called yet 请注意, return result的末尾没有() ,因此该函数尚未调用
  3. The function gets called in print(f(1)) and the variable x takes 1 as its value 该函数在print(f(1))被调用,变量x取值为1
  4. Finally the result function returns the computed value using x , and a , b and c (from square_fun(1, 2, 3) ) 最后,结果函数使用xabc (来自square_fun(1, 2, 3) )返回计算值。

You can find additional info here => https://www.learnpython.org/en/Closures 您可以在此处找到其他信息=> https://www.learnpython.org/en/Closures

You can also use functools.partial : 您还可以使用functools.partial

from functools import partial


def square_fun(x, a, b, c):
    return a * x ** 2 + b * x + c


f = partial(square_fun, a=1, b=2, c=3)
print(f(1))
# should print 6

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

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