013 decorator (key)

Keywords: Python

;

##Closure: internal function, calling variables outside the scope of other functions

def  outer():
    x=10
    def  inner():
        print(x)
    return   inner
#outer()()
f=outer()

f()

Here inner is a closure, closure = internal function + environment, and environment is x=10.
Closures are used to explain the phenomenon of calling variables that are not in their scope

##Decorator

 1 import  time
 2 def  show_runtime(func):
 3     def  inner():
 4         start_time=time.time()
 5         time.sleep(1)
 6         func()
 7         end_time=time.time()
 8         print(end_time-start_time)
 9     return  inner
10 
11 def  f():
12     print('aiq')
13 
14 f=show_runtime(f)         #decorate f function
15 f()

The show uuruntime() method is a decorator
Use on tall:

@show_runtime  # Be equal to f=show_runtime(f),It 's decorated
def  f():
    print('aiq')

#For the parameters in the decorator, add parameters to the inner function, as well as the functions in the inner

import  time
def  show_runtime(func):
    def  inner(*x,**y):
        start_time=time.time()
        func(*x,**y)
        end_time=time.time()
        print(end_time-start_time)
    return  inner

@show_runtime               #Be equal to f=show_runtime(f)
def  add(*a,**b):
    sum=0
    for  i  in  a:
        sum+=i
    print(sum)
    time.sleep(1)
add(3,5,7)
import  time
def  logger(flag=False):
    def  show_runtime(func):
        def  inner(*x,**y):
            start_time=time.time()
            func(*x,**y)
            end_time=time.time()
            print(end_time-start_time)
            if  flag==True:                #If the tag is True Then execute
                pass
        return  inner
    return  show_runtime

@logger(True)    #Equal to call first logger Function, and then execute@show_time,It's like a closure, calling external variables
def  add(*a,**b):
    sum=0
    for  i  in  a:
        sum+=i
    print(sum)
    time.sleep(1)
add(3,5,7)

 

Job:

 1 # __author: _nbloser
 2 # date: 2017/12/25
 3 # username, passwd = 'xia', 123  # It's in the file
 4 def read_user_messege(file_name):
 5     f = open(file_name)
 6     data = eval(f.read())
 7     f.close()
 8     return data
 9 
10 
11 def logger(auth_type='jingdong'):
12     def decorator(func):
13         def inner():
14             global status_login
15             if status_login == False:
16                 username_input = input('input username:')
17                 user_table = read_user_messege(''.join([auth_type, '.txt']))
18                 if username_input in user_table:
19                     passwd_input = input('input passwd:')
20                     if user_table[username_input] == passwd_input:
21                         status_login = True
22                         func()
23                     else:
24                         print('Password error, login failed!')
25                 else:
26                     print('There is no such user')
27             if status_login == True:
28                 func()
29 
30         return inner
31 
32     return decorator
33 
34 
35 @logger()
36 def home():
37     print("welcome,  home page.")
38 
39 
40 @logger('wechat')
41 def finance():
42     print('finance.')
43 
44 
45 @logger()
46 def book():
47     print('book')
48 
49 
50 status_login = False
51 while True:
52     print('1:home\n'
53           '2:finance\n'
54           '3:book\n'
55           'others:exit\n')
56     elect = input('>>>')
57     if elect == '1':
58         home()
59     elif elect == '2':
60         finance()
61     elif elect == '3':
62         book()
63     else:
64         break

 

jingdong.txt: {'xia': 'aiq', 'q': 'aix'}

wechat.txt: {'xia': 'wh_aiq', 'q': 'wh_aix'}

 

Example in the supplementary book: because there is no foundation for this, I feel that I am familiar with writing more.

 1 # __author: _nbloser
 2 # date: 2017/12/25
 3 
 4 def foo(f):
 5     """foo function Docstring"""
 6 
 7     def wrapper(*x, **y):
 8         """wrapper  doc"""
 9         print('Call function:', f.__name__)
10         return f(*x, **y)
11 
12     return wrapper
13 
14 @foo
15 def bar(x):
16     return x**2
17 
18 if __name__=='__main__':
19     print(bar(2))
20     print(bar.__name__)
21     print(bar.__doc__)
 1 # __author: _nbloser
 2 # date: 2017/12/25
 3 
 4 def outter(func):
 5     def inner(*x, **y):
 6         print('aiq')
 7         func(*x, **y)
 8 
 9     return inner
10 
11 
12 @outter
13 def my_add(a, b):
14     print(a + b)
15 
16 
17 if __name__ == '__main__':
18     my_add(2, 8)
 1 # __author: _nbloser
 2 # date: 2017/12/25
 3 
 4 import time, functools
 5 
 6 
 7 def timeit(func):
 8     def wrapper(*args):
 9         start = time.perf_counter()
10         func(*args)
11         end = time.perf_counter()
12         print('Run time:', end - start)
13 
14     return wrapper
15 
16 
17 @timeit
18 def my_sum(n):
19     sum = 0
20     for i in range(n):
21         sum += i
22     print(sum)
23 
24 
25 if __name__ == '__main__':
26     my_sum(10000)
 1 # __author: _nbloser
 2 # date: 2017/12/25
 3 
 4 import time
 5 
 6 
 7 def outer(func):
 8     def inner(*args):
 9         start_time = time.time()
10         func(*args)
11         time.sleep(1)
12         end_time = time.time()
13         print('Run time:', end_time - start_time)
14 
15     return inner
16 
17 
18 @outer
19 def my_factorial(n):
20     product = 1
21     for i in range(2, n):
22         product *= i
23     print(product)
24 
25 
26 my_factorial(25)
 1 # __author: _nbloser
 2 # date: 2017/12/25
 3 def make_bold(func):
 4     def wrapper(*args):
 5         return ''.join(['<b>', func(*args), '<b/>'])
 6 
 7     return wrapper
 8 
 9 
10 def make_italic(func):
11     def wrapper(*args):
12         return ''.join(['<i>', func(*args), '</i>'])
13 
14     return wrapper
15 
16 
17 @make_bold
18 @make_italic
19 def html_tags(str1):
20     return str1
21 
22 
23 print(html_tags('hello'))
24 # Operation result:<b><i>hello</i><b/>

Posted by ag3nt42 on Sun, 03 May 2020 16:18:52 -0700