首页 > 编程语言 >Python - Lambda expressions as closures

Python - Lambda expressions as closures

时间:2024-07-31 17:21:11浏览次数:8  
标签:function username Python closures func expressions expression lambda

A closure is a nested function that can access free variables from an enclosing function even after it has finished its execution. We know that, like nested function definitions, lambda expressions can reference values from the enclosing scope, so lambda expressions are also useful as a closure.

def func(x, username):
     if x < 0:
        return lambda: print('Hello', username)
     elif x > 0:
        return lambda: print('Hi', username)
     else:
        return lambda: print('Hey', username)


f1 = func(6, 'Sam')
f1()
f2 = func(0, 'Tim')
f2()

Output-

Hi Sam

Hey Tim

We can use the parameter username inside the lambda expression, so here these lambda expressions act as closures. Here is one more example:

def func(symbol):
   return lambda message: print(message + symbol)


exclaim = func('!!!!!')
question = func('???')
sentence = func('.')
exclaim('OMG')
question('What is this')
sentence('Python is easy')
exclaim('Really')

Output-

OMG!!!!!

What is this???

Python is easy.

Really!!!!!

The lambda expression remembers the value of the symbol from the enclosing scope even after the flow of control is not in that scope; thus, it acts as a closure.

The function func returns a function object. That function object is created by the lambda expression. message is the parameter of the lambda expression and symbol is the parameter of the function func. We have called the function func 3 times, first time with argument '!!!!!', second time with argument '???' and third time with argument '.'. These arguments will be assigned to the parameter symbol when func is called.

When the function func is executed, the lambda expression creates a function object which is returned by func. We have assigned the returned function objects to the names exclaim, question, and sentence. These names now act like functions and we call them with different arguments. The arguments that are sent to these function calls, are assigned to the parameter message of lambda expression.

 

标签:function,username,Python,closures,func,expressions,expression,lambda
From: https://www.cnblogs.com/zhangzhihui/p/18335033

相关文章

  • Python - Creating jump tables using lambda functions
    Wecanplacelambdafunctioninsidelistanddictionaryliterals.Thiswaywecanuselambdaexpressionstocreatejumptables.>>>L=[lambdas:s.strip().lower(),... lambdas:s.strip().upper(),... lambdas:s.lstrip().title(),... lambd......
  • exceptionx:灵活便捷的Python异常处理库,让异常处理更高效!
    exceptionxEnglish|中文exceptionx是一个灵活且便捷的Python异常处理库,允许你动态创建异常类,并提供多种异常处理机制。exceptionx的前身是gqylpy-exception。pip3installexceptionx动态创建异常使用exceptionx,你可以在需要时即时创建异常类,而无需提前定义。例如,如......
  • systempath:Python开发者必备的文件与系统路径操作神器!
    systempath-专业级的文件与系统路径操作库English|中文systempath是一个专为Python开发者设计的,高度专业化的文件与系统路径操作库。通过提供一套直观且功能强大的面向对象API,它极大地简化了复杂文件与目录管理的任务,使开发者能够更专注于核心业务逻辑的实现,而非底层文件系......
  • 用Python打造精彩动画与视频,3.3 添加音频和简单效果
     3.3添加音频和简单效果在本节中,我们将学习如何使用MoviePy库为视频添加音频和一些简单的效果。这些操作可以让你的视频更具吸引力和个性化。准备工作首先,确保你已经安装了MoviePy和pydub库。你可以通过以下命令安装:pipinstallmoviepypydub同时,你需要确保系统......
  • 用Python打造精彩动画与视频,3.2 基本的剪辑和合并操作
     3.2基本的剪辑和合并操作在这一节中,我们将学习如何使用MoviePy库对视频进行基本的剪辑和合并操作。MoviePy是一个用于视频编辑的Python库,可以轻松地实现视频的剪辑、合并、添加音频等操作。准备工作首先,确保你已经安装了MoviePy库。你可以通过以下命令安装:pipins......
  • 计算机毕业设计django/flask导师双选指导系统python+vue
    通过分析企业对于本科生导师指导平台的需求,创建了一个计算机管理本科生导师指导平台的方案。文章介绍了本科生导师指导平台的系统分析部分,包括可行性分析等,系统设计部分主要介绍了系统功能设计和数据库设计。 Python版本:python3.7+前端:vue.js+elementui框架:django/flask都......
  • 农产品商城自主供销服务系统 微信小程序-python+uniapp
    小程序端运行软件 微信开发者工具/hbuiderxuni-app框架:使用Vue.js开发跨平台应用的前端框架,编写一套代码,可编译到Android、小程序等平台。农产品供销系统是基于微信小程序开发,本系统分为用户,管理员,商家三个角色;用户功能是注册登陆后,在线购买商品,加入购物车,生成订单,在线咨......
  • VSCode:Python 虚拟环境未在集成终端中自动激活
    我最近安装了VSCode,并注意到当我打开集成终端时,Python虚拟环境不会自动激活。从此链接中VSCode内提供的信息:https://github.com/microsoft/vscode-python/wiki/Activate-Environments-in-Terminal-Using-Environment-Variables看来Python扩展可能不会对......
  • Python 中的多元回归
    我想在Python中基于多个相关数据数组和多个独立数据执行多元线性回归。我见过很多多重线性回归,具有多个独立输入,几乎每个人都认为多重=多元,但事实并非如此。我在互联网上看不到任何真正的多元教程。我想要的是多个输出+多个输入。frompandasimportDataFramefromsklear......
  • Python 复选框和 Excel
    我有一个Python系统,它收集用户的条目,进行计算并显示结果。当用户单击条目数据按钮时,所有数据条目和结果都会转换为Excel。在系统界面中有是部分的复选框,结果显示在Excel中。我需要一个助手来编写代码,以便我可以在每次用户选择选定的复选框时转换结果,将复选框的每......