一、默认参数
python为了简化函数的调用,提供了默认参数机制:
def pow(x, n = 2): r = 1 while n > 0: r *= x n -= 1 return r
这样在调用pow函数时,就可以省略最后一个参数不写:
print(pow(5)) # output: 25
在定义有默认参数的函数时,需要注意以下:
必选参数必须在前面,默认参数在后;
设置何种参数为默认参数?一般来说,将参数值变化小的设置为默认参数。
python标准库实践
python内建函数:
print(*objects, sep=' ', end='/n', file=sys.stdout, flush=False)
函数签名可以看出,使用print('hello python')这样的简单调用的打印语句,实际上传入了许多默认值,默认参数使得函数的调用变得非常简单。
二、出错了的默认参数
引用一个官方的经典示例地址 :
def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_listprint(bad_append('1'))print(bad_append('2'))
这个示例并没有按照预期打印:
['1']['2']
而是打印了:
['1']['1', '2']
其实这个错误问题不在默认参数上,而是我们对于及默认参数的初始化的理解有误。
三、默认参数初始化
实际上,默认参数的值只在定义时计算一次,因此每次使用默认参数调用函数时,得到的默认参数值是相同的。
我们以一个直观的例子来说明:
import datetime as dtfrom time import sleepdef log_time(msg, time=dt.datetime.now()): sleep(1) # 线程暂停一秒 print("%s: %s" % (time.isoformat(), msg))log_time('msg 1')log_time('msg 2')log_time('msg 3')
运行这个程序,得到的输出是:
2017-05-17T12:23:46.327258: msg 12017-05-17T12:23:46.327258: msg 22017-05-17T12:23:46.327258: msg 3
即使使用了sleep(1)让线程暂停一秒,排除了程序执行很快的因素。输出中三次调用打印出的时间还是相同的,即三次调用中默认参数time的值是相同的。
上面的示例或许还不能完全说明问题,以下通过观察默认参数的内存地址的方式来说明。
首先需要了解内建函数id(object) :
id(object)
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object in memory.
即id(object)函数返回一个对象的唯一标识。这个标识是一个在对象的生命周期期间保证唯一并且不变的整数。在重叠的生命周期中,两个对象可能有相同的id值。
在CPython解释器实现中,id(object)的值为对象的内存地址。
新闻热点
疑难解答