Python学习笔记------带返回值的装饰器

 

import  time
def timer(func):
    def warper(*args, **kwargs): #args:位置参数 [] kwargs:关键字参数 {} (*args, **kwargs)统称为可变长参数
        start_time = time.time()
        res = func(*args, **kwargs)
        print('args === %s   kwargs ======= %s' %(args, kwargs))
        end_time = time.time()
        print('函数的运行时间=========%s' %(end_time - start_time))
        return  res #test函数的返回值
    return  warper

# @timer
# 无参函数
# def test():
#     time.sleep(3)
#     print('函数执行完毕')
#     return 'test 函数的返回值'
#
#
# res = test()
# print(res)

@timer
def test(name, age):
    time.sleep(3)
    print('姓名是 [%s]  年龄是 [%s]' %(name, age))

@timer
def test1(name, age, gender):
    time.sleep(3)
    print('姓名是 [%s]  年龄是 [%s]  性别是 [%s]' % (name, age, gender))

# res = test('alex', '18')
res = test('alex', age='18')
print(res)


# res1 = test1('alex', '18', 'male')
res1 = test1('alex', age='18', gender='male')
print(res1)

你可能感兴趣的:(编程语言,Python,人工智能)