1.任意个数参数
Python函数可接受任意个数的参数.下面例子演示了两个参数,三个参数时的情形,
>>> def concat(*args, sep="."): return sep.join(args) >>> concat("china","shanghai") 'china.shanghai' >>> concat("china","shanghai","pudong") 'china.shanghai.pudong' >>>
2.参数列表的分解
当函数的参数是一个列表(list)或者元组(tuple)时,我们需要使用类似指针的形式来传递参数。
>>> list(range(3, 6)) [3, 4, 5] >>> args = [3, 6] >>> list(range(*args)) [3, 4, 5] >>> def f(a, b='b', c='c'): print(a) print(b) print(c) >>> d = {"a": "this is a", "b": "this is b", "c": "this is c"} >>> f(**d) this is a this is b this is c >>>
上述例子中,我们使用*或者**的形式传递参数,*是针对列表或者元组的,**是面对字典Dictionary的。这种形式非常灵活,值得借鉴。
3.获取函数的注释
>>> def getDoc(): ''' This is comments this is another comments''' >>> print(getDoc.__doc__) This is comments this is another comments >>>
4.pass关键字
pass关键字的用法顾名思义,什么事情都不做
>>> def funPass(): pass >>> funPass() >>>
5.CodeStyle
1)使用四个space缩进,不要使用tab;
2)每一行不超过79个字符;
3)使用空行分隔函数和类,以及函数中的大的代码块;
4)尽可能针对行进行注释;
5)尽可能使用文档字符串;
6)在运算符和注释后使用空格;
7)类和函数命名一致;类首字母大写;函数小写;
8)使用通用的编码形式,Python默认是UTF-8;
9)不要使用非ASCII编码字符;