python中的函数
来源:互联网 发布:计算机加密软件 编辑:程序博客网 时间:2024/05/19 01:13
python doc上的内容
默认参数
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使用的时候可以想下面那样使用:
- giving only the mandatory argument: ask_ok('Doyoureally wanttoquit?')
- giving one of the optional arguments: ask_ok('OKtooverwrite the file?', 2)
- or even giving all arguments: ask_ok('OKtooverwrite the file?', 2, 'Come on, only yes or no!')
<pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="p">[]):</span> <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="k">return</span> <span class="n">L</span><span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>输出将是下面的形式,这显然不是想要的结果。
[1][1, 2][1, 2, 3]
关键字参数
位置参数就如下面函数的vlotage参数,关键字参数就是kwarg=value这种形式,例如:
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) # 1 positional argumentparrot(voltage=1000) # 1 keyword argumentparrot(voltage=1000000, action='VOOOOOM') # 2 keyword argumentsparrot(action='VOOOOOM', voltage=1000000) # 2 keyword argumentsparrot('a million', 'bereft of life', 'jump') # 3 positional argumentsparrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
但是下面的就是不合法的调用方式:
parrot() # required argument missingparrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argumentparrot(110, voltage=220) # duplicate value for the same argumentparrot(actor='John Cleese') # unknown keyword argument
需要注意的是,一个参数只能进行一次设置,关键字参数的设置左边的变量名必须是定义函数内的变量名,关键字参数的位置可以任意,但是位置参数的位置不能任意。
函数参数中的*name和**name这种格式的参数用法
*name必须出现在**name前面
*name将接收的参数放在tuple中
而**name将接受到的参数放在字典中
例子:
def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in <strong>arguments</strong>: print arg print "-" * 40 keys = sorted(<strong>keywords</strong>.keys()) 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 LimburgerIt's very runny, sir.It's really very, VERY runny, sir.----------------------------------------client : John Cleeseshopkeeper : Michael Palinsketch : Cheese Shop Sketch
Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (seeTuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.
def write_multiple_items(file, separator, *args): file.write(separator.join(args))
Unpacking Argument Lists
>>> 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"} #from a dic>>> parrot(**d)-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
Lambda Expressions
lambdaa,b: a+b : this return the sum of a and b
例子:
>>> def make_incrementor(n):... return lambda x: x + n...>>> f = make_incrementor(42)>>> f(0)42>>> f(1)43
另外lamda表达式可以作为函数实参使用
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]>>> pairs.sort(key=lambda pair: pair[1])>>> pairs[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
0 0
- [Python]Python函数参数中的*,**
- Python:python中的随机数函数
- python中的exec 函数
- python中的函数对象
- python中的lambda函数
- Python中的一些函数
- python中的reduce函数
- Python函数参数中的*,**
- Python中的range()函数
- python中的专有函数
- python 中的函数
- Python中的随机函数
- Python中的函数柯里化
- Python中的main函数
- python中的lambda函数
- Python中的函数
- Python中的range函数
- python中的property函数
- Android学习之SQLite练习(一)
- 配置pydot环境
- bzoj 2818: Gcd
- PyMel技术集锦
- 我的第一个c++
- python中的函数
- HTTP Basic Authentication认证的资源的C#实现
- nyoj 79 拦截导弹
- Linux中weblogic中axis.jar的冲突的解决办法
- 如何成为数据科学家( http://gkkgo.com/guide/44)
- Python--垃圾回收机制
- 避免NullPointException
- 逗比学树莓派之GPIO
- LeetCode之Maximum Product Subarray