?定義
返回單值
def my_abs(x):
if x >= 0:
return x
else:
return -x
返回多值
返回多值就是返回一個(gè)tuple
import math
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
空函數(shù)
?
def nop():
pass
指定默認(rèn)參數(shù)
必選參數(shù)在前,默認(rèn)參數(shù)在后。默認(rèn)參數(shù)需指向不可變對(duì)象(默認(rèn)參數(shù)值在函數(shù)定義時(shí)被計(jì)算)
?
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
可變參數(shù)
?
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
調(diào)用可變參數(shù)的函數(shù)方法
?
>>> calc(1, 2)
5
>>> calc()
0
>>> nums = [1, 2, 3]
>>> calc(*nums)
14
關(guān)鍵字參數(shù)
?
def person(name, age, **kw):
print 'name:', name, 'age:', age, 'other:', kw
調(diào)用關(guān)鍵字參數(shù)的方法
?
>>> person('Michael', 30)
name: Michael age: 30 other: {}
>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
>>> kw = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **kw)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
注:
??? 參數(shù)定義的順序必須是:必選參數(shù)、默認(rèn)參數(shù)、可變參數(shù)和關(guān)鍵字參數(shù)。
??? 對(duì)于任意函數(shù),都可以通過(guò)類似func(*args, **kw)的形式調(diào)用它,無(wú)論它的參數(shù)是如何定義的。
遞歸
如果一個(gè)函數(shù)在內(nèi)部調(diào)用自身本身,這個(gè)函數(shù)就是遞歸函數(shù)。
尾遞歸
在函數(shù)返回的時(shí)候,調(diào)用自身本身,并且,return語(yǔ)句不能包含表達(dá)式。
高階函數(shù)
- ??? 變量可以指向函數(shù)(函數(shù)可以賦值給一個(gè)變量)
- ??? 函數(shù)名也是變量(函數(shù)名可以賦值其他值)
- ??? 函數(shù)可以做為函數(shù)的參數(shù)(高階函數(shù))
map(func, list)
map()函數(shù)接收兩個(gè)參數(shù),一個(gè)是函數(shù),一個(gè)是序列,map將傳入的函數(shù)依次作用到序列的每個(gè)元素,并把結(jié)果作為新的list返回。
?
>>> def f(x):
... return x * x
...
>>> map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce(func_with_two_params, list)
reduce把一個(gè)函數(shù)作用在一個(gè)序列[x1, x2, x3…]上,這個(gè)函數(shù)必須接收兩個(gè)參數(shù),reduce把結(jié)果繼續(xù)和序列的下一個(gè)元素做累積計(jì)算。
?
reduce(f, [x1, x2, x3, x4])
#相當(dāng)于:
f(f(f(x1, x2), x3), x4)
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
filter(func_return_bool, list)
把傳入的函數(shù)依次作用于每個(gè)元素,然后根據(jù)返回值是True還是False決定保留還是丟棄該元素。
?
def is_odd(n):
return n % 2 == 1
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
# 結(jié)果: [1, 5, 9, 15]
sorted
對(duì)于兩個(gè)元素x和y,如果認(rèn)為x < y,則返回-1,如果認(rèn)為x == y,則返回0,如果認(rèn)為x > y,則返回1,
?
>>> sorted([36, 5, 12, 9, 21])
[5, 9, 12, 21, 36]
高階函數(shù)用法
?
def reversed_cmp(x, y):
if x > y:
return -1
if x < y:
return 1
return 0
>>> sorted([36, 5, 12, 9, 21], reversed_cmp)
[36, 21, 12, 9, 5]
函數(shù)做為返回值
?
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
>>> f()
25
注:每次調(diào)用lazy_sum()都會(huì)返回一個(gè)新的函數(shù),即使傳入相同的參數(shù)。
閉包
?
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
>>> f1()
9
>>> f2()
9
>>> f3()
9
原因是調(diào)用count的時(shí)候循環(huán)已經(jīng)執(zhí)行,但是f()還沒(méi)有執(zhí)行,直到調(diào)用其時(shí)才執(zhí)行。所以返回函數(shù)不要引用任何循環(huán)變量,或者后續(xù)會(huì)發(fā)生變化的變量。
匿名函數(shù)(lambda表達(dá)式)
?
等價(jià)于:
?
def f(x):
return x * x
關(guān)鍵字lambda表示匿名函數(shù),冒號(hào)前面的x表示函數(shù)參數(shù)。
匿名函數(shù)做為返回值
?
def build(x, y):
return lambda: x * x + y * y
裝飾器(@func)
在代碼運(yùn)行期間動(dòng)態(tài)增加功能的方式,稱之為“裝飾器”(Decorator),本質(zhì)上,decorator就是一個(gè)返回函數(shù)的高階函數(shù)。
?
def log(func):
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
@log
def now():
print '2013-12-25'
>>> now()
call now():
2013-12-25
#相當(dāng)于執(zhí)行:
now = log(now)
回到頂部
帶參數(shù)的裝飾器
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print '%s %s():' % (text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def now():
print '2013-12-25'
#執(zhí)行結(jié)果
>>> now()
execute now():
2013-12-25
#相當(dāng)于執(zhí)行:
>>> now = log('execute')(now)
剖析:首先執(zhí)行l(wèi)og('execute'),返回的是decorator函數(shù),再調(diào)用返回的函數(shù),參數(shù)是now函數(shù),返回值最終是wrapper函數(shù)。
?
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
#對(duì)于帶參函數(shù)
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s():' % (text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
偏函數(shù)(固定函數(shù)默認(rèn)值)
?
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
#相當(dāng)于:
def int2(x, base=2):
return int(x, base)
max2 = functools.partial(max, 10)
相當(dāng)于為max函數(shù)指定了第一個(gè)參數(shù)
?
max2(5, 6, 7)
#相當(dāng)于:
max(10, 5, 6, 7)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

