python def用法_Python 10 个极简用法,第四期

前三期,请参考:

Python 10 个习惯用法,第一期

Python 10 个习惯用法,第二期

Python 10 个习惯用法,第三期

1 生成一个数字序列

如下生成一个从10到1的逆序序列:

In [3]: for i in range(10,0,-1):
   ...:     print(i)
   ...:
10
9
8
7
6
5
4
3
2
1

2 pass 使用场景

通常用于创建最小的类

In [4]: class TestPass():
   ...:     pass
   ...:

In [5]: TestPass()
Out[5]: <__main__.testpass>0x1b5f67b1b48>

还可用作函数的占位符:

In [7]: def testPassFun():
   ...:     pass
   ...:

In [8]: testPassFun()

3 def 创建函数

Python 使用 def 创建函数,def 也是使用频率最高的操作符之一。如下 fg 函数创建斐波那契数列序列

In [12]: def fg(n):
    ...:     i = 0
    ...:     a,b=0,1
    ...:     while i    ...:         yield b
    ...:         a,b = b, a+b
    ...:         i+=1

In [13]: for i in fg(10):
    ...:     print(i)
1
1
2
3
5
8
13
21
34
55  

4 移花接木

abs 是Python内置函数,如果abs被赋值为自定义函数,会发生什么。

创建 myabs 函数,与 abs 实现操作相反

In [9]: def myabs(x):
   ...:     return x if x 0 else -x
   ...:

In [10]: myabs(1)
Out[10]: -1

In [11]: myabs(-1)
Out[11]: -1

如果 abs 被赋值为 myabs,它将与 myabs 功能一样


In [12]: abs=myabs

In [13]: abs(-1)
Out[13]: -1

5 函数默认值

In [15]: def cube(length,width,height=1):
    ...:     return length*width*height
    ...:

In [16]: cube(1,2) # 高度值默认为 1
Out[16]: 2

In [17]: cube(1,2,3) # 一旦被赋值,高度值将不再是默认值
Out[17]: 6

6 默认值一般不用列表

注意:Python默认值只会执行一次,所以默认值为可变对象时,会出现如下现象:

In [18]: def defaultParaList(a,lst=[]):
    ...:     lst.append(a)
    ...:     return lst
    ...:

In [19]: defaultParaList(1)
Out[19]: [1]

In [20]: defaultParaList(3)
Out[20]: [1, 3]

In [21]: defaultParaList(5)
Out[21]: [1, 3, 5]

7 关键字参数

Python 中参数形如 a=1 来调用函数,被称为关键字参数:

In [15]: def cube(length,width,height=1):
    ...:     return length*width*height
    ...:
    
In [25]: cube(1,width=2) # width这样赋值为关键字参数
Out[25]: 2

注意并不是说 width 一定为关键字参数,如上被赋值才是关键字参数。

8 位置参数

In [15]: def cube(length,width,height=1):
    ...:     return length*width*height
    ...:
    
In [25]: cube(1,2) # width这样赋值为位置参数
Out[25]: 2

9 赋值习惯错误

位置参数不能位于关键字参数后面:

In [15]: def cube(length,width,height=1):
    ...:     return length*width*height
    ...:
In [23]: cube(length=1,2)
  File "", line 1
    cube(length=1,2)
                 ^
SyntaxError: positional argument follows keyword argument

10 可变参数

含一个*或两个*的参数,如下参数虽只有2个,但是第一个参数因为带一个星号,所以能传入任意多个参数,sep 为默认形参。

In [34]: def concat(*words,sep=','):
    ...:     return sep.join(words)

In [35]: concat('i','love','python')
Out[35]: 'i,love,python'

以上就是 10 个习惯用法,第四期。码字不易,点个在看。

程序员从0学算法,就关注下面公众号:

cbaf348616fd058a1d8c0980d481cf04.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值