Decorative Device
The essence of the adorner is a Python function that adds functionality to the function while not making any modifications to the original function. The return value of the adorner is also a function object.
Category: 1, adorner functions without parameters:
defWrapper (f):#Decorative Device defInner): " "what to do before executing a function" "print (' gourd baby gourd, a cane on the seven baby. ')
RET= f () " "what to do after the function is executed""
Print (' The wind and rain are not afraid, La la la la ~ ') returnretreturnInner@wrapper#语法糖@wrapper equivalent to Func = Wrapper (func)deffunc (*args,**kwargs):Print("Macau's top casino on-line, sexy dealer online licensing, so you hi-wow ~") func ()#func () = inner () call adorner
Calculation Result:
Gourd Baby gourd, a cane on the seven dolls.
Macau's top casino on-line, sexy dealer online licensing, so you hi-wow ~
The wind and rain are not afraid, La la la la ~
where wrapper () is the adorner function, func () is a decorated function, and after being decorated func () can implement part of the function in inner.
2. Adorner function with parameters:
defTimer (func):defInner (*args,**Kwargs):Print("Big head son small small father, a pair of good friends happy father and son two. ") ret= Func (*args,**Kwargs)Print("the son's head is very small, the father's head small hand is very big. ") returnretreturnInner@timerdeffunc (name):Print("%s is Uncle Wang next door ."%name) func ("Wang Wenjing") calculation result: Big head son small little father, a pair of good friends happy father and son two. Wang Wenjing is the next door Uncle Wang son's head big hand son is very small, father's head small hand is very big.
principle : Open and closed principle
1, open: To expand is open, you can add new features (adorners)
2, Closed: The modification is closed, can not easily modify the previous code
Application: User Login detection
Application--Login detection: USER,PW='Jaye',' 88888888'Login_status=Falsedeflogin ():ifLogin_status = =False:ifAuth_type = ="Jingdong"username=input () password=input ()ifuser = = Username andPW = =Password:Print('Welcome to Moubao Store') Home () Login_status=TrueelifAuth_type = ="Weixin" ... Else: Pass@login (Auth_type='jingodng')defHome ():Print('Welcome to Home Page') @login (Auth_type='Weixin')defFinance ():Print('Welcome to Home Page') @login (Auth_type='jingodng')defBook ():Print('Welcome to Home Page')
Python function Learning Decorator