Python快速而美丽[v1.0.0][Lambda]

“Lambda 表达式”(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。

返回俩数之和

return_result_of_plus = lambda a, b: a + b

返回任意数字加100

return_result_any_number_plus_100 = lambda x: x+100

返回任意参数个数之和

return_length_of_any_two_arguments = lambda *args, **kwargs: len(args)+len(kwargs)

实现简单分支

return_result_of_one_branch = lambda a, b: a if a > b else b
browser_driver = lambda browser: webdriver.Chrome() if browser == 'chrome' else webdriver.Firefox()

Lambda应用于列表

list_lambda = [lambda x: x+100, lambda x: x+200, lambda x: x+300]

代码示例

# -*- coding: utf-8 -*-
# @Time    : 11/22/2019 7:18 PM
# @Author  : davieyang
# @Email   : [email protected]
# @File    : How_To_Use_Lambda.py
# @Project: UI_AUTOMATION
from selenium import webdriver


class How_To_Use_Lambda:
    """
    show something about 'lambda' by real function
    """

    return_result_of_plus = lambda a, b: a + b
    return_result_any_number_plus_100 = lambda x: x+100
    return_length_of_any_two_arguments = lambda *args, **kwargs: len(args)+len(kwargs)
    return_result_of_one_branch = lambda a, b: a if a > b else b
    list_lambda = [lambda x: x+100, lambda x: x+200, lambda x: x+300]  # define list of python by lambda
    browser_driver = lambda browser: webdriver.Chrome() if browser == 'chrome' else webdriver.Firefox()


if __name__ == '__main__':
    unittest_lambda = How_To_Use_Lambda
    print(unittest_lambda.return_result_of_plus(2019, 2020))
    print(unittest_lambda.return_result_any_number_plus_100(2019))
    print(unittest_lambda.return_length_of_any_two_arguments(2019, 'b', 'c', aaa='bbbb'))
    print(unittest_lambda.return_result_of_one_branch(2019, 2020))
    print(unittest_lambda.list_lambda[0](2019))
    print(unittest_lambda.list_lambda[1](2019))
    print(unittest_lambda.list_lambda[2](2019))
    print(unittest_lambda.browser_driver('chrome'))




你可能感兴趣的:(Python快速而美丽)