tolist函式 十八 深入Python函式

2021-10-12 08:47:43 字數 4628 閱讀 4167

近來,越來越多人使用函式式程式設計(functional programming)。本文對 python 中的函式式程式設計技術進行了簡單的入門介紹。

python內建了很多有用的函式,我們可以直接呼叫。

要呼叫乙個函式,需要知道函式的名稱和引數,比如求絕對值的函式abs,只有乙個引數。

也可以在互動式命令列通過help(abs)檢視abs函式的幫助資訊。

呼叫abs函式:

>>> abs(100)

100>>> abs(-20)

20>>> abs(12.34)

12.34

在python中的函式就是為了實現某一段功能的**段,可以重複利用。

就是以後不要重複造輪子,遇到那個場景就用那個函式,就是函式式程式設計。

下面,我定義乙個 my_func,傳入乙個hello world,再列印乙個hello world

def my_func(message):

print('got a message: {}'.format(message))

# 呼叫函式 my_func()

my_func('hello world')

# 輸出

got a message: hello world

簡單的知識點

「定義在前,呼叫在後」

def my_sum(a, b):

return a + b

result = my_sum(3, 5)

print(result)

# 輸出

8

對於函式的引數可以設定預設值

def func(param = 0):

pass

如果param沒有傳入,那麼引數預設是0,如果傳入了引數,就覆蓋預設值

傳入的引數可以接受任何資料型別

比如,列表

print(my_sum([1, 2], [3, 4]))

# 輸出

[1, 2, 3, 4]

再比如,字串

print(my_sum('hello ', 'world'))

# 輸出

hello world

當然,如果引數資料型別不同,而兩者無法相加

print(my_sum([1, 2], 'hello'))

typeerror: can only concatenate list (not "str") to list

同乙個函式可以應用到整數,列表,字串等等的操作稱為多型。這可不是**。

函式巢狀就是函式中有函式,就叫巢狀函式了。

def f1():

print('hello')

def f2():

print('world')

f2()

f1()

# 輸出

hello

world

函式的巢狀保證了內部函式的呼叫,內部函式只能被外部函式所呼叫,不會作用於全域性域中。

合理使用函式巢狀,提高運算速度

比如計算5的階乘。

def factorial(input):

if not isinstance(input, int):

raise exception('input must be an integer.')

if input < 0:

raise exception('input must be greater or equal to 0' )

def inner_factorial(input):

if input <= 1:

return 1

return input * inner_factorial(input-1)

return inner_factorial(input)

print(factorial(5))

120

如果變數是izai函式內部定義的,稱為區域性變數,只在函式內部有效,當函式執行完畢,區域性變數就會被**。

全域性變數就是寫在函式外面的。

min_value = 1

max_value = 10

def validation_check(value):

if value < min_value or value > max_value:

raise exception('validation check fails')

這裡的min_velue 和max_value就是全域性變數,但是我們不能在函式的內部隨意改變全域性變數的值

min_value = 1

def validation_check(value):

min_value += 1

validation_check(5)

報錯:unboundlocalerror: local variable 'min_value' referenced before assignment

要想改變 必須加上global這個宣告

min_value = 1

def validation_check(value):

global min_value

min_value += 1

validation_check(5)

global告訴python解析器,函式內部的變數min_value就是定義的全域性變數,這裡輸入的是2,這樣修改的全域性變數的值

min_value = 1

max_value = 10

def validation_check():

min_value = 3

print(min_value)

validation_check()

print(min_value)

# 3# 1

對於巢狀函式來說,內部函式無法修改外部函式定義的變數,可以訪問,想要修改就要加上 nonolocal

def outer():

x = "local"

def inner():

nonlocal x # nonlocal 關鍵字表示這裡的 x 就是外部函式 outer 定義的變數 x

x = 'nonlocal'

print("inner:", x)

inner()

print("outer:", x)

outer()

# 輸出

inner: nonlocal

outer: nonlocal

不加就不會覆蓋

def outer():

x = "local"

def inner():

x = 'nonlocal' # 這裡的 x 是 inner 這個函式的區域性變數

print("inner:", x)

inner()

print("outer:", x)

outer()

# 輸出

inner: nonlocal

outer: local

函式的閉包其實和函式的巢狀很相似。和巢狀不同,閉包的外部函式返回是乙個函式,而不是乙個具體的值。

閉包就是在函式裡面呼叫函式,一般用return來執行,return出內部呼叫的函式名。

def nth_power(exponent):

def exponent_of(base):

return base ** exponent

return exponent_of # 返回值是 exponent_of 函式

square = nth_power(2) # 計算乙個數的平方

cube = nth_power(3) # 計算乙個數的立方

square

# 輸出

.exponent(base)>

cube

# 輸出

.exponent(base)>

print(square(2)) # 計算 2 的平方

print(cube(2)) # 計算 2 的立方

# 輸出

4 # 2^2

8 # 2^3

當然,我們也可以通過乙個函式來寫這個功能:

def nth_power(base,exponent):

return base**exponent

但是,使用閉包,可以讓程式變得更加簡潔易懂。 ❞

[1]

傳送門~:

python order函式 Python函式之二

關鍵字引數 kwargs def foo kw if y in kw print kw y foo x 123,y 1232 如上面的示例關鍵字引數用於函式呼叫,通過 鍵 值 形式加以指定。這種方式可以根據傳入的引數來決定函式的執行方向。可以讓函式更加清晰 容易使用,同時也清除了引數的順序需求,及時...

python中full函式 Python函式混亂

我正在學習 python.我有乙個函式readwrite filename,list filename的型別為string.list是乙個包含要在檔案中重寫的字串的列表.我有乙個簡單的函式呼叫,如下所示 fname hello.txt readwrite xx fname,datalist 我面臨的...

python常用函式 enumerate函式

1 如果對乙個列表,既要遍歷索引又要遍歷元素時,首先可以這樣寫 list1 這 是 乙個 測試 for i in range len list1 print i list1 i 2 上述方法有些累贅,利用enumerate 會更加直接和優美 list1 這 是 乙個 測試 for index,ite...