python編程基礎之二十八
阿新 • • 發佈:2018-08-09
分享 函數代碼 函數名 調用 順序 包含 turn python編程 裝飾器
裝飾器:說白了就是閉包,但是內部函數調用外部變量調用的是函數,
好處:就是在不用修改原函數代碼的前提下給函數增加新的功能
裝飾器有兩種寫法
第一種:
1 #被修飾的函數 2 def say_hello(name): 3 print(‘我就是人見人愛,花見花開的%s‘%name) 4 5 # 參數是被修飾函數 6 def wrapper(func): #1.定義裝飾器 7 def inner(name): #2.定義閉包 在閉包中增加功能 8 print(‘-‘ * 50) 9 func(name) #View Code3.調用原函數實現原來的功能 10 print(‘*‘ * 50) 11 return inner #4.返回增強功能的函數 12 13 say_hello = wrapper(say_hello) #5.獲取增強功能的函數 14 say_hello(‘張三‘) #6. 調用增強函數,實現功能
第二種:
1 def wrapper(func): 2 def inner(age1): 3 #增加的功能 4 if age1 < 0: 5 age1 = 0 6 #View Code調用原函數 7 func(age1) 8 return inner 9 10 @wrapper #相當於 getAge = wrapper(getage) 11 def getAge(age): 12 print(age) 13 getAge(18) #調用增強的函數
直接在被修飾的函數定義前加@修飾器函數名
多個修飾器函數修飾同一個函數
記得修飾順序按照遠近順序就行,近的先修飾
1 def wrapper1(func): 2 print("wrapper1~~~~外部函數") 3 def inner(a,b):View Code4 print(‘wrapper1-----內部函數‘) 5 func(a,b) 6 return inner 7 8 def wrapper2(func): 9 print("wrapper2~~~~外部函數") 10 def inner(a, b): 11 print("wrapper2~~~~內部函數") 12 func(a, b) 13 return inner 14 15 @wrapper1 16 @wrapper2 17 def text(num1,num2): 18 print(num1 + num2) 19 20 text(10,20)
遞歸:一個函數直接或間接調用自己,遞歸分為正向遞歸,逆向遞歸兩個過程
一個遞歸一定包含兩個部分:遞歸結束條件,遞歸調用自己
1 def recurve(*args,**kw): 2 if 遞歸終止條件: #遞歸終止條件必須在遞歸調用前 3 # to do 4 else: 5 #to do 6 recurve(參數) 7 #to doView Code
python編程基礎之二十八