函數(shù)和函數(shù)式編程
函數(shù)
聲明函數(shù):
def hello():
print("hello function!")
調(diào)用函數(shù):
# 使用()調(diào)用
hello()#output:hello function!
# 沒有(),則不進(jìn)行調(diào)用,一切皆是對象,函數(shù)也是對象
print(hello)#output:<function hello at 0x000001EE36F1B3A0>
hello#output:<function __main__.hello()>
print(hello.__class__)#output:<class 'function'>
print(type(hello))#output:<class 'function'>
print(type(hello()))
#output:
#hello function!
#<class 'NoneType'>
xxx = hello
print(xxx.__name__)#output:hello
函數(shù)—可變不可變對象
可更改(mutable)與不可更改(immutable)對象
在python中, strings, tuples,和 numbers是不可更改的對象,而list,dict等則是可以修改的對象。
- **不可變類型:**變量賦值 a=5 后再賦值 a=10,這里實(shí)際是新生成一個 int 值對象 10,再讓 a 指向它,而 5 被丟棄,不是改變a的值,相當(dāng)于新生成了a。
- **可變類型:**變量賦值 la=[1,2,3,4] 后再賦值 la[2]=5 則是將 list la 的第三個元素值更改,本身la沒有動,只是其內(nèi)部的一部分值被修改了。
python 函數(shù)的參數(shù)傳遞:
- **不可變類型:**類似 c++ 的值傳遞,如 整數(shù)、字符串、元組。如fun(a),傳遞的只是a的值,沒有影響a對象本身。比如在 fun(a)內(nèi)部修改 a的值,只是修改另一個復(fù)制的對象,不會影響 a 本身。
- **可變類型:**類似 c++的引用傳遞,如列表,字典。如fun (la),則是將 la 真正的傳過去,修改后fun外部的la也會受影響python 中一切都是對象,嚴(yán)格意義我們不能說值傳遞還是引用傳遞,我們應(yīng)該說傳不可變對象和傳可變對象。
可變類型:
def changeme(mytest_List):
mytest_List.append([1, 2, 3, 4])
print("函數(shù)內(nèi)取值:", mytest_List)
return
#調(diào)用changeme函數(shù)
mytest_List = [100, 200, 300]
print(mytest_List)
changeme(mytest_List)
print("函數(shù)外取值:", mytest_List)
#output:
#[100, 200, 300]
#函數(shù)內(nèi)取值: [100, 200, 300, [1, 2, 3, 4]]
#函數(shù)外取值: [100, 200, 300, [1, 2, 3, 4]]
不可變類型:
def change_int(a):
a = 10
b = 3
change_int(b)
print(b)
#output:3
函數(shù)—參數(shù)
-
必備參數(shù)
-
定義
def func(p): print(f"p is {p}")
-
調(diào)用
func(1)#output:p is 1 func(p=1)#output:p is 1
-
-
默認(rèn)參數(shù)
def func(a, b=1, c=2): print(f"a={a}, b={b}, c={c}") func(1, 1, 1) func(1, c=1) func(1) # output: # a=1, b=1, c=1 # a=1, b=1, c=1 # a=1, b=1, c=2
-
可變參數(shù)
def func(a, *args, **kwargs): print(f"a={a}, args={args}, kwargs={kwargs}") func(1, 1, 1) func(1, c=1) func(1) func(1, 2, 3, x=8) # output: # a=1, args=(1, 1), kwargs={} # a=1, args=(), kwargs={'c': 1} # a=1, args=(), kwargs={} # a=1, args=(2, 3), kwargs={'x': 8}
-
可變參數(shù)調(diào)用
# *變量名 元組傳入?yún)?shù) args = (0, 10, 2) print(list(range(*args))) # output: # [0, 2, 4, 6, 8] # **變量名 字典傳入?yún)?shù) from datetime import datetime print(datetime(year=1999, month=7, day=1)) # output: # 1999-07-01 00:00:00 kwargs = {"year":1999, "month":7, "day":1} print(datetime(**kwargs)) # output: # 1999-07-01 00:00:00
函數(shù)—函數(shù)返回值
在函數(shù)體內(nèi)使用return語句可以從函數(shù)中返回一個值并跳出函數(shù)的功能。
- 多條return語句:
return語句可以放在函數(shù)中任何位置,當(dāng)執(zhí)行到第一個return語句時程序返回到調(diào)用程序。
- 返回多個值:
如果需要返回多個值,則可以返回一個元組。
函數(shù)—Built-in 函數(shù)
內(nèi)置函數(shù):
函數(shù)—作用域
-
LEGB解析順序:Local, Enclosing, Global, Built-in
-
global關(guān)鍵字
total = 100 # 這是一個全局變量 def sum(arg1, arg2): total = arg1 + arg2 # 這里是局部變量 print("函數(shù)內(nèi)是局部變量:", total) return total sum(10, 20) print("函數(shù)外是全局變量:", total) # output: # 函數(shù)內(nèi)是局部變量: 30 # 函數(shù)外是全局變量: 100
注意:
- 全局變量大寫首字母,局部變量全小寫
- 不要使用Built-in和關(guān)鍵字作變量/函數(shù)名
- python中print函數(shù)需要返回值,如果你在print函數(shù)中沒有返回值,那么print將會return None
全局語句global
在函數(shù)體中可以引用全局變量,但如果函數(shù)內(nèi)部的變量名時第一次出現(xiàn)在賦值語句之前(變量賦值),則解釋為定義局部變量。
如果要為定義在函數(shù)外的全局變量賦值,可以使用global語句,表明變量是在外面定義的全局變量。global語句可以指定多個全局變量。
#全局變量
Pi = 3.1415
E =2.71828
def my_func():
global Pi #全局變量,于前面的全局變量Pi指向相同對象
Pi = 3.1 #改變?nèi)肿兞康闹?/span>
print("global Pi= ", Pi)#輸出全局變量值
E = 2.7 #局部變量,與前面的全局變量E指向不同的對象
print("local E = ", E)#輸出局部變量值
print("module Pi= ", Pi)
print("module E= ", E)
my_func()
print("module Pi= ", Pi)# 輸出全局變量的值,該值在函數(shù)中已被更改
print("module E= ", E)
# output:
# module Pi= 3.1415
# module E= 2.71828
# global Pi= 3.1
# local E = 2.7
# module Pi= 3.1
# module E= 2.71828
非局部語句nonlocal
在函數(shù)體中可以定義嵌套函數(shù),在嵌套函數(shù)中如果要為定義在上級函數(shù)體的局部變量賦值,可以使用nonlocal語句,表明變量不是所在塊的局部變量,而是在上級函數(shù)體中定義的局部變量。
# module E= 2.71828
#%%
def outer_func():
tax_rate = 0.17 #上級函數(shù)體中的局部變量
print("outer func tax rate= ", tax_rate)#輸出上級函數(shù)體中局部變量的值
def inner_func():
nonlocal tax_rate # 不是所在塊的局部變量,而是在上級函數(shù)體中定義的局部變量
tax_rate = 0.05 # 上級函數(shù)體中的局部變量重新賦值
print("inner func tax rate= ", tax_rate) # 輸出上級函數(shù)體中局部變量的值
inner_func()
print("outer func tax rate= ", tax_rate) # 輸出上級函數(shù)體中局部變量的值(已更改)
outer_func()
# output:
# outer func tax rate= 0.17
# inner func tax rate= 0.05
# outer func tax rate= 0.05
函數(shù)式編程
函數(shù)式編程
input -> f1 -> f2 -> f3 ->f4 -> f5 -> output
函數(shù)式編程vs面向?qū)ο缶幊?/strong>
- First-class function,簡化很多設(shè)計模式
- 更簡單的函數(shù)-更好編寫和維護(hù)
- 更容易做單元測試
- 更容易跨線程,跨進(jìn)程,甚至跨機(jī)器執(zhí)行任務(wù)
匿名函數(shù)
lambda
優(yōu)勢:結(jié)構(gòu)體簡單,函數(shù)體簡短場景適用,即用即棄文章來源:http://www.zghlxwxcb.cn/news/detail-530242.html
a = [0, 1, 2, 3, 4, 5]
result = filter(lambda x: x % 2 == 0, a)
print(list(result))
# output:[0, 2, 4]
- filter()
filter(func, lst)函數(shù)?于過濾序列, 過濾掉不符合條件的元素, 返回?個 fifilter 對象,。如果要轉(zhuǎn)換為列表文章來源地址http://www.zghlxwxcb.cn/news/detail-530242.html
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def func(x):
return x % 2 == 0
result = filter(func, list1)
print(result)
print(list(result))
到了這里,關(guān)于Python基礎(chǔ):函數(shù)和函數(shù)式編程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!