1. 程式人生 > >Python學習——函式

Python學習——函式

Python函式

1、程式碼重用 2、保持一致性 3、可擴充套件性

def f(a,b=x,*c,**d):
	pass
#  a 必需引數
#  b 預設引數(預設引數)
#  c 不定長引數
#  a必須在b和d的左邊,b必須在a的右邊d的左邊,c必須在a 的右邊d的左邊

def f(a,*b,c=x,**d):
	pass

如果單獨出現星號 * 後的引數必須用關鍵字傳入。

>>> def f(a,b,*,c):
...     return a+b+c
... 
>>> f(1,2,3)   # 報錯
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 3 were given
>>> f(1,2,c=3) # 正常
6
>>>

作用域

LEGB

Local區域性作用域 函式中定義的變數 Enclosing巢狀的父級函式的區域性作用域 Global全域性變數,模組級別定義的變數 Built-in 最外層,系統固定模組裡面的變數

變數搜尋的順序為 LEGB (自內由外)

訪問全域性 global

>>> a=10
>>> def f():
...     def ff():
...             global a
...             a=5
...     ff()
...
>>> a
10
>>> f()
>>> a
5
>>>

訪問父級區域性變數 nonlocal (python3新增,閉包)

高階函式

在數學和電腦科學中,高階函式是至少滿足下列一個條件的函式: 接受一個或多個函式作為輸入 輸出一個函式

閉包

如果在一個內部函式裡,對在外部作用域(但不是在全域性作用域)的變數進行引用,那麼內部函式就被認為是閉包(closure)

>>> def outer():
...     a=10
...     def inner(): #條件一:一個內部函式
...             nonlocal a #條件二:外部環境的一個變數
...             print(a)
...             a-=5
...     return inner
...
>>> f=outer()
>>> f()
10
>>> f()
5
>>> f()
0
>>> f()
-5

內建函式

filter()

str=['a','b','c','d']
def func(s):
	if s!='a':
		return s
res=filter(func,str)
print(res)

map()

reduce(function,seq) from functools import reduce

>>> def f(a,b):
...     return a+b
... 
>>> reduce(f,range(1,10))
45
>>> 

lambda

lambda x,y:x+y

def f(x,y):
	return x+y

>>> reduce(lambda x,y:x*y,range(1,10))
362880
>>>