闭包函数,装饰器

一.闭包函数

  一个函数在另一个函数体内,就是嵌套函数

  我把一个函数叫做内部函数,另一个函数叫做外部函数

  内部函数可以调用外部函数所有的变量和参数这就叫做闭包函数

  1.第一种给给函数传值   传参

# def my_len(x):
#     print(x)
#     # n = 0
#     # for i in x:
#     #     n += 1
#     # print(n)
# my_len('hello')

  2.第二种给函数传参  闭包函数

# def index():
#     x = 2
#     y = 3
#     def func():
#         if x > y:
#             return x
#         return y
#     return func
# res = index()
# # print(res)  # <function index.<locals>.func at 0x000002B9042229D8>
# print(res())

  

  内部函数func可以调用外部函数的变量名x,y

作用意义:内部函数不论在何处被调用,优先使用的是外部函数的作用域

二.装饰器

  好比工具,给函数添加功能

  必须遵循的原则:

    1:不能更改被装饰函数的调用,就是函数名加括号不变

    2.不能更改被装饰函数的代码

        def index():
            pass
        index()

  1.装饰器的模板

# def outer(func):
#     def inter(*args,**kwargs):
#         print('执行被装饰之前 你可以做的操作')
#         res = func(*args,**kwargs)
#         print('执行被装饰函数之后 你可以做的操作')
#         return res
#     return inter

  2.有参和无参

# 将被装饰的函数(无参)
# import time
# def index():
#     time.sleep(1)
#     print('hello world')

# 将被装饰的函数(有参)*args,**kwargs
# def login(name):
#     time.sleep(1)
#     print('%s is a good man'%name)
#     return 'hello'

# 装饰器
# def outer (func):
#     def my_time(*args,**kwargs):
#         start = time.time()
#         func(*args,**kwargs)  # func = index函数的地址  函数名加括号直接调用
#         end = time.time()
#         print('index程序运行的时间是:%s'%(end-start))
#     return my_time
# index = outer(index)  # outer(index的地址)
# index()
# print(index)  # <function outer.<locals>.my_time at 0x000001498C362AE8>
# login = outer(login)
# login('egon')

  3.装饰器语法糖和修补功能

     1.@+装饰器函数名后面没有括号,放在紧挨着被装饰函数的上面      

       2,首先在装饰器前写一个  , from functools import wraps 

       然后在装饰器的内部和外部函数之间加上@wraps(func)括号内为参数

  修补功能的两个作用:

    1.用户查看被装饰器装饰函数的函数名时,看到的是被装饰函数的本身
        print(index.__name__)  # 查看函数名 以字符串形式
    2.用户查看被装饰函数的注释时,查看到的是被装饰函数的注释
        print(help(index))  # 查看注释内容
from functools import wraps
def outer (func):
    @wraps(func)
    def my_time(*args,**kwargs):
        start = time.time()
        res = func(*args,**kwargs)  # func = index函数的地址  函数名加括号直接调用
        end = time.time()
        print('index程序运行的时间是:%s'%(end-start))
    return my_time

# 被装饰的函数
# import time
# @outer  # login = outer(login)
# def login(name):
#     time.sleep(1)
#     print('%s is a good man'%name)
#     return 'hello'
# login('egon')

# 被装饰的函数
import time
@outer  # index = outer(index)
def index():
    """
    index 的注释
    :return:
    """
    time.sleep(1)
    print('hello world')
index()
print(help(index))
print(index.__name__)

猜你喜欢

转载自www.cnblogs.com/zhuangshenhao/p/11172835.html