Decorator and anonymous functions:
Example: counting function implemented:
DEF defunc (FUNC): Print ( ' ------------------- Hello ' ) COUNT = 0 DEF Mapper (* args, ** kwargs): nonlocal COUNT Print ( ' Welcome to call the function of the {} {} times ' .format (FUNC. the __name__ , COUNT)) FUNC (* args, ** kwargs) COUNT + =. 1 return Mapper @defunc DEF show (): Print ( ' which is a function of show ... ' ) for I in Range (. 3 ): Show () '' ' ------------------- the Hello welcome to call the show function 0th This is a function show ... welcome to call the show the first time the function which is a function show ... welcome to call the show function 2nd this is a function of ... show '' '
1, * args ** kwargs used in the function of
If you want to achieve universal decorator function, you need to add the function of the variable parameter in the inner layer
Whether this function is decorated parameters or no parameters, or have keyword parameters can be decorated
2, to be decorated function returning the inner layer must also have a function of decorator return value, so as to ensure the function and the original function decorative consistency.
Example: decorator user's login authentication:
islogin = False def login_requierd(func): def wrapper(*args, **kwargs): global islogin if islogin: func(*args, **kwargs) else: print('-----------用户没有登录,请登录') f = login() if f: func(*args, **kwargs) return wrapper def login(): global islogin username = input(' Please enter your name: ' ) password = INPUT ( ' Enter password: ' ) IF username == ' Gang ' and password == ' 123 ' : islogin = True return islogin return islogin @login_requierd DEF buy_ticket (): Ticket = { ' Zhongguancun: ' : ( ' Rebels ' , [ ' 11:35 hall 1 ' , ' 12:15 hall II' , ' 13:45 Hall III ' ])} for Key, value in ticket.items (): Print ( " Cinema " , Key) Print ( ' play movie is ' , value [0]) Print ( ' Playback time is: ' ) for I in value [. 1 ]: Print ( ' ---> ' , I) # Login () buy_ticket () ' '' ----------- user is not logged Please login Please enter your user name: gang Please enter the password: 123 theater Zhongguancun: The movie is playing Rebels playing time are: ---> 11:35 Hall 1 ---> 12:15 II hall ---> Hall 13:45 III '' '
3, decorator parameters: three functions that are implemented
def decorator name (parameters): def SECOND, (arguments): def THIRD, (* args, ** kwargs): .... .... return THIRD, return SECOND,
def decorator(number): print('------>1') def decorator1(func): print('------->2') def wrapper(*args, **kwargs): print('-----start') func(*args, **kwargs) print('--------end') print('-------->3') return wrapper print('------->. 4 ' ) return decorator1 @decorator ( 10 ) DEF show (): Print ( ' -------> function call show ' ) show () ' '' ----- ->. 1 ------->. 4 -------> 2 -------->. 3 ----- Start -------> show function calls - End ------ '' '
4, the multilayer decorator:
Who recently performed the first decorator from which the original function will return the first layer of a decorator's results to the second layer decorators
Last: address of the original function of the second layer is obtained return value wrapper
DEF decorator1 (FUNC): DEF warpper (* args, ** kwargs): FUNC ( * args, ** kwargs) Print ( ' brush floor ' ) Print ( ' painting ' ) return warpper DEF decorator2 (FUNC): DEF warpper (* args, ** kwargs): FUNC ( * args, ** kwargs) Print ( ' buy furniture ' ) Print ( ' buy sofa ' ) Print (' Buy decorations ' ) return wrapper @ decorator2 @ decorator1 DEF House (): Print ( ' ---------- not decorate the house ' ) Print (House) House () ' '' <function decorator2 <. about locals> .wrapper AT 0x000001A795094510> ---------- not decorate the house brush floor painting buy furniture, buy a sofa to buy decorations ' ''
5, an anonymous function:
Definition Format: the lambda Parameters: Return Value
Use: 1, the function body 2 is very simple, lesser frequency of use
f = lambda n:n+1 print(f) r = f(5) print(r) f1 = lambda x,y:x+y r = f1(1,2) print(r)
example:
list1 = [('tom',12),('lucy',20),('lily',16),('luze',19),('jerry',34)] list2 = sorted(list1,key=lambda x:x[1],reverse=True) print(list2) #[('jerry', 34), ('lucy', 20), ('luze', 19), ('lily', 16), ('tom', 12)]
As a function of the parameters passed to the function: 6, higher-order functions
1 "sorted (iterable, key, reverse) parameter which is a function key
dict1 = {'tom':12,'lucy':20,'lily':16,'luze':19,'jerry':34} result = sorted(dict1.items(),key=lambda x:x[1]) dict1 = dict(result) print(dict1) #{'tom': 12, 'lily': 16, 'luze': 19, 'lucy': 20, 'jerry': 34}
2》map映射 map(function,iterable)
Iteration to the subject a can, by the action of the function, which is transformed into a new object
map1 = map(lambda x: x ** 2, [1, 2, 3, 4, 5]) print(map1) print(list(map1)) # <map object at 0x0000023D21830C18> # [1, 4, 9, 16, 25] names = ['tom', 'java', 'c#', 'python'] map2 = map(lambda x: x.capitalize(), names) print(list(map2)) # ['Tom', 'Java', 'C#', 'Python'] map0 = map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]) print(list(map0)) # [5, 7, 9]
3 "filter (function, iterable): The return value is a filter
We need to convert Return Value: list (filter_object)
function return value of the function must be of type bool
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, 13, 24] filter1 = filter(lambda x: x % 2 == 0, num) print(list(filter1)) # [2, 4, 6, 8, 0, 10, 24]
list1 = ['hello', 67, 'nihao', '99', '25', 'gang'] filter1 = filter(lambda x: str(x).isdigit(), list1) print(list(filter1)) # [67, '99', '25'] filter2 = filter(lambda x: isinstance(x, int) or x.isdigit(), list1) print(list(filter2)) # [67, '99', '25']
4》reduce(function,iterable)
Function is a function of the parameters, the parameters of this function must be two lambda x, y: x * y
Iterable argument is an iterable
from functools import reduce list1 = [1, 2, 3, 5] result = reduce(lambda x, y: x + y, list1, 2) print(result) # 13 result = reduce(lambda x, y: x + y, range(1, 7)) print(result) # 21
7, functools module
partial () function is a partial section through a function parameter pre-bound to some value, to obtain a new variable function with less parameters.
from functools import partial,wraps int1 = partial(int,base=8) print(int1('123')) # 83
wraps () eliminate some of the side effects caused by decorators
Get Object Name: house .__ name__ get the function name house .__ doc__ obtain documentation comments
python decorator: in the realization of the function after being decorated in fact already is another function of (name of the function and other functions attributes will change) in order not to affect, python's functools package provides a decorator called wraps to eliminate such side effects.
from functools Import partial, Wraps DEF decorator1 (FUNC): @wraps (FUNC) DEF wrapper (* args, ** kwargs): FUNC ( * args, ** kwargs) Print ( ' shop floor ' ) Print ( ' painting ' ) return wrapper DEF house (): Print ( ' ---------- not decorate the house ' ) Print . house ( __name__ ) Print . (house __doc__ ) house () # House # None # ---------- not decorate the house
8, the list is derived formula:
Format: [expression for i in list | set | tuple | dict [if condition]]
Format: [Expression 1 if condition else expression 2 for i in list | set | tuple | dict [if condition]]
格式:[表达式 for i in list|set|tuple|dict for i in list|set|tuple|dict ]
list1 = [1,3,5,2,5,7] list2 = [x for x in list1 if x%2==0] print(list2) #[2] list3 = [x+1 if x%2==0 else x+2 for x in list1] print(list3) # [3, 5, 7, 3, 7, 9] list0 = [1,2,3] list4 = [2,4,6] list5 = [(x,y) for x in list0 for y in list4] print(list5) # [(1, 2), (1, 4), (1, 6), (2, 2), (2, 4), (2, 6), (3, 2), (3, 4), (3, 6)]