零基础学习python偏函数语法的推导方法步骤
作者:村长 时间:2021-07-17 20:59:18
Python偏函数
Python偏函数和我们之前所学习的函数传参中的缺省参数有些类似,但是在实际应用中还是有所区别的,下面通过模拟一个场景一步一步的推导先来看看偏函数的语法形成。
需求:新生入学,需要录入学生姓名和所在班级,大多数学生都是同一个班级。
第一步:一个一个学生资料录入;
print('我是%s,我在%d班' % ('张三', 2))
print('我是%s,我在%d班' % ('李四', 2))
print('我是%s,我在%d班' % ('王五', 2))
第二步:使用函数来录入;
def new_stu(name, cla):
print('我是%s,我在%d班' % (name, cla))
new_stu('张三', 2)
new_stu('李四', 2)
new_stu('王五', 2)
第三步:如果某个班级学生偏多,可以使用缺省参数来完成
def new_stu(name, cla=2):
print('我是%s,我在%d班' % (name, cla))
new_stu('张三', 3)
new_stu('李四')
new_stu('王五')
通过上面三步之后其实我们已经实现偏函数的效果了,这里再补充一点通过functools模块实现普通函数的偏函数效果,注意内部注释。
# 4.通过functools修改第2步的函数
import functools
new_student = functools.partial(new_stu, cla=2) # 通过partial指定new_stu里面的cla是偏爱参数
new_student(name='张三', cla=5)
new_student('李四') # 被偏爱的参数最好放在后面,否则按顺序传容易出错
new_student(name='王五') # 先把name传给new_stu函数
来源:http://www.wakey.com.cn/document-func-deviate.html
标签:python,偏函数,语法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何使用七牛Python SDK写一个同步脚本及使用教程
2021-01-19 12:51:13
![](https://img.aspxhome.com/file/2023/8/81468_0s.png)
PHP5 mysqli的prepare准备语句使用说明
2023-11-22 12:50:29
python Django框架快速入门教程(后台管理)
2022-04-17 11:43:12
![](https://img.aspxhome.com/file/2023/2/76102_0s.png)
数据库技巧——MySQL十大优化技巧
2011-01-31 16:44:00
![](https://img.aspxhome.com/file/UploadPic/20111/2011131175530832s.jpg)
Python实现实时显示进度条的六种方法
2022-03-27 02:09:35
![](https://img.aspxhome.com/file/2023/2/70112_0s.jpg)
利用Python实现绘制论文中的曲线图
2022-12-14 12:04:37
![](https://img.aspxhome.com/file/2023/9/78489_0s.png)
ASP使用MYSQL数据库全攻略
2009-11-08 18:27:00
将有安全问题的SQL过程删除,比较全面
2007-08-06 14:46:00
pygame实现弹球游戏
2023-05-26 20:38:44
如何取得表中字段的属性?
2010-01-18 20:52:00
Go语言中的匿名结构体用法实例
2023-07-07 11:10:21
合并网页中的多个script引用实现思路及代码
2023-06-29 09:02:19
解决bootstrap导航栏navbar在IE8上存在缺陷的方法
2023-09-03 10:55:07
![](https://img.aspxhome.com/file/2023/0/56080_0s.gif)
asp中文URL编码server.urlencode
2008-08-08 11:22:00
如何将服务器端变量转换为客户端的变量?
2009-12-03 19:54:00
show一下刚做的系统登录界面
2008-09-13 19:13:00
![](https://img.aspxhome.com/file/UploadPic/20089/13/2008913191851666s.png)
多栏自适应布局问题浅谈
2010-08-16 12:56:00
![](https://img.aspxhome.com/file/UploadPic/20108/16/two_column_layout-58s.png)
零基础学python应该从哪里入手
2023-04-27 20:44:56
浅谈购物类网站如何保持视觉设计的一致性
2009-03-30 16:02:00
![](https://img.aspxhome.com/file/UploadPic/20093/30/14-52s.jpg)
Python线程池thread pool创建使用及实例代码分享
2022-02-26 00:43:35
![](https://img.aspxhome.com/file/2023/9/69569_0s.png)