Python Function
def addition(x, y):
return x + y
Python Lambda
addition_lambda = lambda x, y: x + y
lambda
keyword
- Parameters list
(any valid Python parameters)
- Single expression
Python Lambda
class Calculator:
@staticmethod
def addition(x, y):
return x + y
def operate_binary(self, a, b, operation):
return operation(a, b)
@staticmethod
def main():
calc = Calculator()
subtraction = lambda x, y: x - y
print("40 + 2 = {}".format(calc.operate_binary(40, 2, Calculator.addition)))
print("20 - 10 = {}".format(calc.operate_binary(20, 10, subtraction)))
print("7 * 6 = {}".format(calc.operate_binary(7, 6, lambda: x, y: x * y)))
if __name__ == "__main__":
Calculator.main()
Python Lambda
def process_persons(roster, filter, mapper, action):
for p in roster:
if filter(p):
data = mapper(p)
action(data)
process_persons(roster,
lambda p: (p.gender == MALE and
p.age >= 18 and
p.age <= 25),
lambda p: p.email_address,
lambda p: print(email))