python-装饰器骗局

装 饰 器 骗 局

Python 函数装饰器:https://www.runoob.com/w3cnote/python-func-decorators.html
装饰器的本意:
加上装饰器—>除了自身功能还有被装饰的内容
不加装饰器—>只有自身的功能

先来看一个装饰器的使用范例:

#计算程序运算时间的装饰器 --- 需要有一个形参 接受待验证运行时间的函数
def get_time(func):
    def wrapper():
        import time
        start = time.time()
        func()
        stop = time.time()
        print("执行时间", stop - start)
    return wrapper

'''
怎么为对应的功能添加装饰器
    使用@语法糖  在被需要添加装饰器的功能上方 @装饰器的外部函数
'''
@get_time
def print_nine_table():
    for r in range(1, 10):
        for c in range(1, r + 1):
            print(f"{c} * {r} = {r*c}", end="\t")
        print()
print_nine_table()

在这里插入图片描述
在这里插入图片描述

装饰器----->原有函数功能增加 or 函数重构 ?

咱们先来看下 Python 中的函数的一些操作:

def hi(name="yasoob"):
    return "hi " + name

print(hi())
# output: 'hi yasoob'

# 我们甚至可以将一个函数赋值给一个变量,比如
greet = hi
# 我们这里没有在使用小括号,因为我们并不是在调用hi函数
# 而是在将它放在greet变量里头。我们尝试运行下这个

print(greet())
# output: 'hi yasoob'

# 如果我们删掉旧的hi函数,看看会发生什么!
del hi
print(hi())
# outputs: NameError

print(greet())
# outputs: 'hi yasoob'

在函数中定义函数:

def hi(name="yasoob"):
    print("now you are inside the hi() function")

    def greet():
        return "now you are in the greet() function"

    def welcome():
        return "now you are in the welcome() function"

    print(greet())
    print(welcome())
    print("now you are back in the hi() function")


hi()
# output:now you are inside the hi() function
#       now you are in the greet() function
#       now you are in the welcome() function
#       now you are back in the hi() function

# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。
# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如:

greet()
# outputs: NameError: name 'greet' is not defined

从函数中返回函数:

def hi(name="yasoob"):
    def greet():
        return "now you are in the greet() function"

    def welcome():
        return "now you are in the welcome() function"

    if name == "yasoob":
        return greet
    else:
        return welcome


a = hi()
print(a)
# outputs: <function greet at 0x7f2143c01500>

# 上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
# 现在试试这个

print(a())
# outputs: now you are in the greet() function

将函数作为参数传给另一个函数:

def hi():
    return "hi yasoob!"


def doSomethingBeforeHi(func):
    print("I am doing some boring work before executing hi()")
    print(func())


doSomethingBeforeHi(hi)
# outputs:I am doing some boring work before executing hi()
#        hi yasoob!

装饰器实例:

def a_new_decorator(a_func):
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")

        a_func()

        print("I am doing some boring work after executing a_func()")

    return wrapTheFunction


def a_function():
    print("I am the function which needs some decoration to remove my foul smell")


a_function()
# outputs: "I am the function which needs some decoration to remove my foul smell"
 
a_function =a_new_decorator(a_functionn)
# now a_function is wrapped by wrapTheFunction()

a_function()
# outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

语法糖@:

@a_new_decorator
def a_function():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")


a_function()
# outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()

# the @a_new_decorator is just a short way of saying:
a_function=  a_new_decorator(a_function)

重构的问题:函数被warpTheFunction替代了。它重写了我们函数的名字和注释文档(docstring)

print(a_function.__name__)
# Output: wrapTheFunction

functools.wraps的引入:

from functools import wraps

def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")

    return wrapTheFunction
@a_new_decorator
def a_function():
    """Hey yo! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")

print(a_function.__name__)
# Output: a_function

综上所述:装饰器本质上是通过程序内容上的一系列操作,把某一个函数的函数体进行了重写,只是名称还是当初那个函数名称,对于计算机来说,只要函数名称一样就会执行相应的函数.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值