初學(xué)Python函數(shù)的筆記整理
定義
返回單值
def my_abs(x):
if x >= 0:
return x
else:
return -x
返回多值
返回多值就是返回一個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
指定默認參數(shù)
必選參數(shù)在前,默認參數(shù)在后。默認參數(shù)需指向不可變對象(默認參數(shù)值在函數(shù)定義時被計算)
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ù)、默認參數(shù)、可變參數(shù)和關(guān)鍵字參數(shù)。
對于任意函數(shù),都可以通過類似func(*args, **kw)的形式調(diào)用它,無論它的參數(shù)是如何定義的。
遞歸
如果一個函數(shù)在內(nèi)部調(diào)用自身本身,這個函數(shù)就是遞歸函數(shù)。
尾遞歸
在函數(shù)返回的時候,調(diào)用自身本身,并且,return語句不能包含表達式。
高階函數(shù)
- 變量可以指向函數(shù)(函數(shù)可以賦值給一個變量)
- 函數(shù)名也是變量(函數(shù)名可以賦值其他值)
- 函數(shù)可以做為函數(shù)的參數(shù)(高階函數(shù))
map(func, list)
map()函數(shù)接收兩個參數(shù),一個是函數(shù),一個是序列,map將傳入的函數(shù)依次作用到序列的每個元素,并把結(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把一個函數(shù)作用在一個序列[x1, x2, x3…]上,這個函數(shù)必須接收兩個參數(shù),reduce把結(jié)果繼續(xù)和序列的下一個元素做累積計算。
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ù)依次作用于每個元素,然后根據(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
對于兩個元素x和y,如果認為x < y,則返回-1,如果認為x == y,則返回0,如果認為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
<function sum at 0x10452f668>
>>> f()
25
注:每次調(diào)用lazy_sum()都會返回一個新的函數(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的時候循環(huán)已經(jīng)執(zhí)行,但是f()還沒有執(zhí)行,直到調(diào)用其時才執(zhí)行。所以返回函數(shù)不要引用任何循環(huán)變量,或者后續(xù)會發(fā)生變化的變量。
匿名函數(shù)(lambda表達式)
等價于:
def f(x): return x * x
關(guān)鍵字lambda表示匿名函數(shù),冒號前面的x表示函數(shù)參數(shù)。
匿名函數(shù)做為返回值
def build(x, y): return lambda: x * x + y * y
裝飾器(@func)
在代碼運行期間動態(tài)增加功能的方式,稱之為“裝飾器”(Decorator),本質(zhì)上,decorator就是一個返回函數(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
#對于帶參函數(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ù)默認值)
>>> 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ù)指定了第一個參數(shù)
max2(5, 6, 7) #相當(dāng)于: max(10, 5, 6, 7)
相關(guān)文章
tensorflow訓(xùn)練中出現(xiàn)nan問題的解決
本篇文章主要介紹了tensorflow訓(xùn)練中出現(xiàn)nan問題的解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
Python3中zip()函數(shù)知識點小結(jié)
本文主要介紹了Python3中zip()函數(shù)知識點小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python有關(guān)Unicode UTF-8 GBK編碼問題詳解
本文主要介紹了Python有關(guān)Unicode UTF-8 GBK編碼問題詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

