Python函数参数
2015-08-26 21:28
651 查看
默认参数
Python提供默认函数参数,例如:def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print complaint
这个函数可以如下调用:
ask_ok('Do you really want to quit?') ask_ok('OK to overwrite the file?', 2) ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
默认参数在函数定义处被计算:
i = 5 def f(arg=i): print arg i = 6 f()
这段程序会输出:5
注意:默认参数值只计算一次,所以,如果默认参数是可变对象(list、dictionary或者对象),那么这个值会被累计:
def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3)
会输出:
[1] [1, 2] [1, 2, 3]
关键字参数
函数可以使用键值对的形式调用,例如: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", type print "-- It's", state, "!"
可以用如下形式调用:
parrot(1000) parrot(action = 'VOOOOOM', voltage = 1000000) parrot('a thousand', state = 'pushing up the daisies') parrot('a million', 'bereft of life', 'jump')
另外,Python还提供了可变参数的调用形式:
def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = keywords.keys() keys.sort() for kw in keys: print kw, ":", keywords[kw]
可以如下调用:
cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper='Michael Palin', client="John Cleese", sketch="Cheese Shop Sketch")
输出如下:
-- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- client : John Cleese shopkeeper : Michael Palin sketch : Cheese Shop Sketch
参数解包
Python函数的参数可以通过对list、dict的解包进行调用,例如:>>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5]
字典如下:
>>> def parrot(voltage, state='a stiff', action='voom'): ... print "-- This parrot wouldn't", action, ... print "if you put", voltage, "volts through it.", ... print "E's", state, "!" ... >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
相关文章推荐
- python进制转换(读取纯二进制文件内容)
- Python读取pcap文件
- java与python在处理大文件操作上的对比
- python多进程编程
- Python多进程编程
- Python多进程编程
- 操作python对象的属性
- Python模块(functools)
- python列表元素去重
- 朴素贝叶斯–分类器
- python排序操作
- 利用Python PIL、cPickle将图片读取和保存为pkl格式文件
- 使用Python进行多进程编程
- python dist-packages 和 site-packages
- 使用python脚本生成随机密码
- Python RE模块
- Python局部变量和全局变量global
- Python中小中花括号的区别
- Python中if __name__ == "__main__":用法解析
- Python文件操作方法