本文主要是介绍The Python Tutorial读书笔记(1)---默认参数的几点需要注意的地方,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
**
The Python Tutorial读书笔记(1)—默认参数的几点需要注意的地方
**
- 在默认的函数形式参数中可以使用以前定义过的变量作为函数形式参数的默认值,具体表现见下:
i = 5def f(arg=i):print argi = 6
f()
#来源于The Python Tutorial
作为解释性语言在在定义函数f的过程中,i 已经存在了,因此绑定的是与函数在同一作用域中的变量的值,不管是全局变量还是临时变量。
- 当可变对象类型作为默认形式参数是会出现不同的差异性如下:
def f(a, L=[]):L.append(a)return Lprint f(1)
print f(2)
print f(3)
#执行结果
[1]
[1, 2]
[1, 2, 3]
也就是说函数绑定了一个空的链表L,当定义函数的后,L分配了固定的地址空间,当调用函数对L进行操作后L的地址空间是没有发生变化的,而前面第一个例子中,i在函数定义的过程中绑定了i的地址空间,在后面定义的i只是一个同名的变量,测试结果如下:
def func():i = 6print id(6)#31826144def tem_func(arg = i):#print argprint id(arg)#31826144i = 7print id(i)#31826120tem_func()i = 10
print id(i)##31826048
func()#结果
#31826048
#31826144
#31826120
#31826144
从结果来看体现了形式参数的依赖于定义前的语句环境。形式参数绑定某一变量。
- 默认参数的位置限制与CC++相同,不过可以使用键值对来进行参数匹配。
如The Python Tutorial一样:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):print "-- This parrot wouldn't", action,print "if you put", voltage, "volts through it."print "-- Lovely plumage, the", typeprint "-- It's", state, "!parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
这篇关于The Python Tutorial读书笔记(1)---默认参数的几点需要注意的地方的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!