Decorators some basic exercises

Original link: http://www.cnblogs.com/dragonff/p/10120269.html

1, a finishing process decorators, fixed format recitation decorator

Copy the code
Fixed format 
def wrapper (func): 2. Incoming function value F 
    DEF Inner (* args, ** kwargs): 
        operation performed before the execution of the function # 
        ret = func (* args, ** kwargs) # 5. performs f ( ) function 
        operation function is executed after the # 
        return ret # 6. function returns a value to the caller of the function name inner ID 
    return through inner # 4. the return value returned by the function call to the inner case = F 
@wrapper #. 1. f = wrapper (f) performing the function wrapper 
DEF F (): 
    Print (666) 
F () 3. perform inner function f () = inner () 

Note: return usage 
1. function encounters the end of the function body return 
2. If return later to keep up with the function name function name in memory of id returns 
3. If you return later to keep up with the other characters of its own return
Copy the code

2, preparation of the decorator, before each print a decorative function being executed 'is performed each time before the first decorative function had been here, where the code is added according to the needs

Press Ctrl + C to copy the code
Press Ctrl + C to copy the code

3, the preparation of decorators, after each execution of the function to print a decorative 'After each decorative function being performed after the first had been here, where the code is added according to the needs

Copy the code
func1 DEF (F): 
    DEF Inner (): 
        F () 
        Print ( 'had to be performed each time after this, where the code is added after the decorative functions according to the needs') 
    return Inner 


@ func1 
DEF func2 (): 
    Print (' Hello World ') 


func2 ()
Copy the code

4, write decorator, allowing users to perform before each decorated function to enter a user name and password, the user three chances, after a successful login to access the function.

Copy the code
func2 DEF (F): 
    DEF innter (): 
        A =. 1 

        the while A <=. 3: 
            username = INPUT ( 'Enter a username') 
            password = INPUT ( 'Enter Password') 
            IF username == 'Jinyuan' and password == '123': 
                F () 
                BREAK 
            the else: 
                Print ( 'error account password you have chance {}' .format (. 3-A)) 
                A + =. 1 
                Continue 
    return innter 


@ func2 
DEF func1 (): 
    Print ( 'Login successful') 


func1 ()
Copy the code

5, write decorators, multiple authentication functions plus functions (from the user's account password file, only supports single user's account password, to the user three chances),
  requires a login is successful, subsequent functions without having to re-enter user name and password

Copy the code
dic = {
    'name':None,
    'status' : False
}

def func1(f):
    def inner(*args,**kwargs):
        num = 0
        while num < 3:
            if dic['status']:
                ret = f(*args,**kwargs)
                return ret
            else:
                username = input('请输入用户名')
                password = input('请输入密码')
                f1 = open('test.txt',encoding='utf-8')
                for i in f1:
                    new_list = i.strip().split()
                    if username == new_list[0] and password == new_list[1]:
                        dic['status'] = True
                        BREAK
                else:
                    +. 1 = NUM 
                    Print ( 'enter a user name or password chance there {}' .format (. 3-NUM)) 
                    Continue 
    return Inner 


@ func1 
DEF Func4 (): 
    Print ( 'successful login') 


Func4 ()
Copy the code

6, for each function writes a log recording function,
functional requirements: before each function call, to function name, time node to log record of the log.
Required modules:
Import Time
struct_time = time.localtime ()
Print (The time.strftime ( "% D%% Y-M-% H:% M:% S", struct_time))

Copy the code
import time
def wapper(f):
    def inner(*args,**kwargs):
        struct_time = time.localtime()
        time_log = time.strftime("%Y-%m-%d %H:%M:%S",struct_time)
        f1 = open('log1.txt',encoding='utf-8',mode='a')
        f1.write(time_log+'\t')
        f1.write(str(f)+'\n')
        f(*args,**kwargs)
    return inner


@wapper
def func1(*args,**kwargs):
    print('hello world')


func1('aa','bbb')

Reproduced in: https: //www.cnblogs.com/dragonff/p/10120269.html

Guess you like

Origin blog.csdn.net/weixin_30906425/article/details/94830257
Recommended