python ----装饰器练习1( 被装饰的函数打印日志信息) 装饰器练习2(判断是否为root用户登录)装饰器练习3(判断变量类型)

"""
 # 创建装饰器, 要求如下:
# 1. 创建add_log装饰器, 被装饰的函数打印日志信息;
# 2. 日志格式为: [字符串时间] 函数名: xxx, 运行时间:xxx, 
#    运行返回值结果:xxx
"""
import time
import functools

def add_log(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kwargs):
        start_time = time.time()
        res = fun(*args,**kwargs)
        end_time = time.time()
        print('[%s] 函数名:%s,运行时间:%.6f,运行返回值结果:%d' %(time.ctime(),
                                                   fun.__name__,end_time - start_time,res))
        return res
    return wrapper

@add_log
def add(x,y):
    time.sleep(1)
    return x+y

print(add(1,10))
# print(time.ctime())

方法1:
def panduan(fun):
    def wrapper(*args,**kwargs):
        if 'root' in args:
             fun(*args,**kwargs)
        else:
            print('error')
    return wrapper
@panduan
def add_student(name):
    print('添加学生信息.....')
add_student('root')

方法2:
import functools
import inspect

def is_root(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kwargs):
        #inspect.getcallargs返回值是字典,key值为:形参,value值为:形参对应实参
        inspect_res = inspect.getcallargs(fun,*args,**kwargs)
        print('inspect_res的返回值为:%s' %inspect_res)
        if inspect_res.get('name') == 'root':
            res = fun(*args,**kwargs)
            return res
        else:
            print('not root user')
    return wrapper

@is_root
def add_student(name):
    print('添加学生信息...')

def del_student(name):
    print('删除学生信息...')

add_student('westos')
"""
编写装饰器required_ints, 条件如下:
    1). 确保函数接收到的每一个参数都是整数;  # 如何判断变量的类型? 
     type(s), isinstance(s,str)
    2). 如果参数不是整形数, 抛出异常raise TypeError(“参数必须为整形”)
"""


def required_ints(fun):
    def wrapper(*args,**kwargs):
        for i in args:
            if not isinstance(i,int):
               raise TypeError('参数必须为整型')
        for i in kwargs.values():
            if not isinstance(i,int):
                raise TypeError('参数必须为整型')
        res = fun(*args,**kwargs)
        return res
    return wrapper
@required_ints
def add(*args,**kwargs):
    return sum(args) + sum(kwargs.values())
print(add(1,2,3,65,1.0,a=1,b=2))

猜你喜欢

转载自blog.csdn.net/yinzhen_boke_0321/article/details/86600452