python装饰器使用例子

装饰器亮点之一是可提取大量函数中与本身功能无关的类似代码,达到代码重用之效。



def dec(func):
    print ("lakers")
    def inner():
        print(" kobebryant111.")
        func()
        print(" kobebryant222.")
        return func()
    print("los ")
    return inner
    
@dec
def myfunc():
    print(" kobebryant.")

myfunc()


输出结果:

lakers
los 
 kobebryant111.
 kobebryant.
 kobebryant222.
 kobebryant.


二 


def dec(func):
    def inner(*arg,**kwarg):
        print("answer:%s<=>%s"%(arg,kwarg))
        return func(*arg,**kwarg)
    return inner
@dec
def f1(x,y):
    return x*y

@dec
def f2():
    print("i am f2()")
    return 100

f1(5,4)

f2()


输出结果:

answer:(5, 4)<=>{}
answer:()<=>{}
i am f2()



三 


import time
def dec(func):
    start=time.time()
    func()
    end=time.time()
    take=end-start
    print("take %f s"%take)

def myfunc():
    print("myfunc start--------")
    time.sleep(3)
    print("myfunc end----------")


dec(myfunc)


输出结果:

myfunc start--------
myfunc end----------
take 3.063872 s



import time
def dec(func):
    def inner():
        start=time.time()      
        func()
        end=time.time()
        take=end-start
        print("take %f s"%take)   
    return inner
def myfunc():
    print("myfunc start--------")
    time.sleep(3)
    print("myfunc end----------")

print("myfunc is ",myfunc.__name__)
myfunc=dec(myfunc)
print ("myfunc is ",myfunc.__name__)

myfunc()


输出结果:

myfunc is  myfunc
myfunc is  inner
myfunc start--------
myfunc end----------
take 3.010637 s



import functools
import time
def dec(func):
    @functools.wraps(func)
    def inner():
        start=time.time()      
        func()
        end=time.time()
        take=end-start
        print("take %f s"%take)   
    return inner
def myfunc():
    print("myfunc start--------")
    time.sleep(3)
    print("myfunc end----------")

print("myfunc is ",myfunc.__name__)
myfunc=dec(myfunc)
print ("myfunc is ",myfunc.__name__)

myfunc()


输出结果:

myfunc is  myfunc
myfunc is  myfunc
myfunc start--------
myfunc end----------
take 3.042459 s

import functools
def text(addtest):
    def dec(func):
        print ("one----------")
        @functools.wraps(func)
        def inner():        
            print("%s"%addtest)
            return func()   
        print("one============ ")
        return inner
    return dec
        
@text("testtext")
def myfunc():
    print(" kobebryant.")

myfunc()
print("myfunc is ",myfunc.__name__)


输出结果:

one----------
one============ 
testtext
 kobebryant.
myfunc is  myfunc



def dec1(func):
    print ("one----------")
    def inner():
        print(" kobebryant111.")
        func()
        print(" kobebryant222.")
        return func()
    print("one============ ")
    return inner

def dec2(func):
    print ("two----------")
    def inner():
        print(" kobebryant333.")
        func()
        print(" kobebryant444.")
        return func()
    print("two============ ")
    return inner
    

@dec2
def myfunc():
    print(" kobebryant.")

myfunc()
print("myfunc is ",myfunc.__name__)


输出结果:

two----------
two============ 
 kobebryant333.
 kobebryant.
 kobebryant444.
 kobebryant.
myfunc is  inner



def dec1(func):
    print ("one----------")
    def inner():
        print(" kobebryant111.")
        func()
        print(" kobebryant222.")
        return func()
    print("one============ ")
    return inner

def dec2(func):
    print ("two----------")
    def inner():
        print(" kobebryant333.")
        func()
        print(" kobebryant444.")
        return func()
    print("two============ ")
    return inner
    
@dec1
@dec2
def myfunc():
    print(" kobebryant.")

myfunc()
print("myfunc is ",myfunc.__name__)


输出结果:

two----------
two============ 
one----------
one============ 
 kobebryant111.
 kobebryant333.
 kobebryant.
 kobebryant444.
 kobebryant.
 kobebryant222.
 kobebryant333.
 kobebryant.
 kobebryant444.
 kobebryant.
myfunc is  inner



def dec(func):
    tmp={}
    def wrap(*args):
        if args not in tmp:
            tmp[args]=func(*args)
        return tmp[args]
    return wrap

@dec
def fib1(n):
    if n==1 or n==0:
        return 1;
    else:
        return fib1(n-2)+fib1(n-1)


def fib2(n,tmp=None):
    if tmp is None:
        tmp={}
    if n in tmp:
        return tmp[n]
    if n==1 or n==0:
        return 1
    else:
        tmp[n]=fib2(n-1,tmp)+fib2(n-1,tmp)  
    return tmp[n]

def fib(n):
    if n==1 or n==0:
        return 1
    else:
        return fib(n-2)+fib(n-1)

    
import time
begin=time.time()
print([fib1(n) for n in range(30)])
end=time.time()
print(end-begin)

begin=time.time()
[fib2(n) for n in range(30)]
end=time.time()
print(end-begin)


begin3=time.time()
[fib(n) for n in range(30)]
end3=time.time()
print(end3-begin3)


输出结果:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]
0.031210899353027344
0.0
0.8125066757202148





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
装饰器Python中一种强大的功能,允许在不修改原始函数的情况下,向函数添加额外的功能。装饰器使用@符号将其应用于函数。 一个装饰器函数通常具有以下形式: ```python def decorator(func): def wrapper(*args, **kwargs): # 添加额外的功能 return func(*args, **kwargs) return wrapper ``` 其中,`decorator`是装饰器函数本身,`wrapper`是内部函数,用于包装原始函数,并添加额外的功能。 装饰器可以应用于函数,类甚至是类的方法。通过在被装饰的函数或方法前使用装饰器函数,可以将装饰器应用于该函数或方法。 例如,引用中的代码展示了一个简单的装饰器模板,引用中的代码展示了一个使用装饰器实现函数计时器的例子。在这个例子中,`timec`是装饰器函数,`wrapper`是内部函数用于计算函数执行的时间。被`timec`装饰的函数`con_add`和`join_add`会在执行前后输出运行时间。 引用中的代码展示了一个包含关键字的装饰器例子。在这个例子中,`decorator`是装饰器函数,`wrapper`是内部函数用于在执行被装饰的函数前后输出时间。被`decorator`装饰的函数`f`接受两个位置参数和任意个关键字参数,并在执行前后输出相应的信息。 总之,装饰器Python中一种强大的功能,可以用于给函数或方法添加额外的功能,而不需要修改原始函数的代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python装饰器使用](https://blog.csdn.net/belong_to_you/article/details/111003741)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python装饰器使用](https://blog.csdn.net/qq_43830639/article/details/95247941)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值