函數與函數式編程:
二種編程模式或是編程方法:
1. 面向對象;=>> 類 =>> 定義class
2. 面向過程;=>> 過程 =》def
3. 函數式編程;最先式編程方法;=>> 函數 =>> def
編程語言中函數的定義:函數是邏輯結構化和國產化的一種編程方法;
def test(x):
"The function definitions"
x += 1
return x
def: #定義函數的關鍵字
test: #函數名:
(): #內能夠定義參數
"": #文檔描述
x += 1: #泛指代碼塊或程序處理過程
return: #定義返回值
# 定義函數
def func1():
"""testing"""
print("in the func1")
return 0
# 定義過程
def func2():
"""testing"""
print("in the func2")
x = func1()
y = func2()
print(x)
print(y)
輸出:
in the func1
in the func2
0
None #python中隱式的給過程定義了返回值。
過程:就是沒有返回值的函數;
在函數中沒有定義返回值的時候,會返回一個None!
函數的優勢:
1. 代碼的重複利用,減小重複代碼:
2. 保持一致性;
3. 可擴展性
def test():
print("in testing ")
return 0 #執行了return就表明函數結束了,後面的代碼將不被執行
print("end in testing")
test()
輸出:
in testing
def test():
print("in testing ")
return 0,"ss",(1,2),[1,2,3] #將返回值打包成一個元組。
a=test()
print(a)
輸出:
in testing
(0, 'ss', (1, 2), [1, 2, 3])
def test():
print("in testing ")
return 0,"ss",(1,2),[1,2,3]
def test1():
print("in testing 1")
return test
print(test1)
輸出:
<function test1 at 0x0350BA08> #此時返回的式test的內存地址,這個對裝飾器頗有做用,就是所謂的高階函數;
帶參數的函數:
def test(x,y): #x, y 是形參
print(x)
print(y)
test(1,2) #1,2 是實參,實際存在;
A. 位置參數:
實參和實參是一一對應的,位置也是一一對應;
def test(x,y):
print(x)
print(y)
test(1,2) #按位置對應
B. 關鍵字參數 def test(x,y): print(x) print(y) test(y=1,x=2) #關鍵字對應。與形參位置不要緊; 若是同時存在關鍵參數和位置參數,關鍵參數是不能放在位置參數前面 也就是說從左往右,位置參數前面不能有關鍵參數。 若是存在關鍵字參數就不論位置了。 C. 默認參數: def test(x,y=1): #即在形參中對對參設置默認值 print(x) print(y) test(1,y=2) 默認參數的特色,調用函數時,默認參數非必須傳值 用途:默認安裝值, D. 參數組: 針對實參不固定的狀況,如何定義形參,即參數組的概念: def test(*args): # *表明一個功能代號,表示實參不固定, args只是一個名字,能夠隨便,但規範是args: print(args) test(1,2,3,4,5) test(*[1,2,3,4]) # *表明一個功能代號,表示實參不固定 輸出: (1, 2, 3, 4, 5) (1, 2, 3, 4) def test(x, *args): print(x) print(args) test(1, 2, 3, 4, 5) test(*[1,2,3,4]) 輸出: 1 (2, 3, 4, 5) # 返回元組 1 (2, 3, 4) 接收字典形參: def test2(**kwargs): # **表明不固定形參爲字典 print(kwargs) test2(name='alex',age='9',gender="female") test2(**{name='alex',age='9',gender="female"}) 輸出: {'name': 'alex', 'age': '9', 'gender': 'female'} # 返回字典 將n個關鍵字參數轉化爲字典的方式。 def test2(**kwargs): print(kwargs["name"]) print(kwargs["age"]) print(kwargs["gender"]) test2(name='alex', age='9', gender="female") 輸出: alex 9 female def test2(x, **kwargs): print(x) print(kwargs) test2(1, name='alex', age='9', gender="female") 輸出: 1 {'name': 'alex', 'age': '9', 'gender': 'female'} def test2(x, age=18, **kwargs): #參數組必須放在位置參數,關鍵字參數後面 print(x) print(age) #關鍵字須要獨立出來,做爲一個獨立的參數 print(kwargs) test2(1, name='alex', age='9', gender="female") 輸出: 1 9 {'name': 'alex', 'gender': 'female'} *args 接收的是N個位置參數轉換爲元組的方式 **kwargs 接收的是N個關鍵字參數轉化爲字典的方式 ===========================================================