python学习笔记(五) 装饰器与迭代器

1、装饰器

定义:是一个闭包,把一个函数当作参数返回一个替代版的函数,本质上就是一个返回函数的函数

简言之,python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。

#简单的装饰器
def func1():
    print("sunck is a good man")

def outer(func):
    def inner():
        print("**********")
        func()
    return inner()

f=outer(func1)

 

复杂一点的装饰器:


def outer(func):
    def inner(age):
        if age < 0:
            age = 0
        func(age)
    return inner

#say = outer(say)


#使用@符号将装饰器应用到函数
#python2.4后支持使用

@outer  #相当于say=outer(say)
def say(age):
    print("sunck is %d years old " %(age))
say(18)
say(-10)

 

通用装饰器:

def outer(func):
	def inner(*args, **kwargs):
		#添加修改的功能
		print("&&&&&&&&&&&")
		func(*args, **kwargs)
	return inner


@outer
def say(name, age):#函数的参数理论上是无限制的,但实际上最好不要超过6、7个
	print("my name is %s,I am %d years old " %(name,age))
say("sunck",18)
#多个装饰器

import time

def deco01(func):
    def wrapper(*args, **kwargs):
        print("this is deco01")
        startTime = time.time()
        func(*args, **kwargs)
        endTime = time.time()
        msecs = (endTime - startTime)*1000
        print("time is %d ms" %msecs)
        print("deco01 end here")
    return wrapper

def deco02(func):
    def wrapper(*args, **kwargs):
        print("this is deco02")
        func(*args, **kwargs)

        print("deco02 end here")
    return wrapper

@deco01
@deco02
def func(a,b):
    print("hello,here is a func for add :")
    time.sleep(1)
    print("result is %d" %(a+b))



if __name__ == '__main__':
    f = func
    f(3,4)
    #func()

'''
this is deco01
this is deco02
hello,here is a func for add :
result is 7
deco02 end here
time is 1003 ms
deco01 end here
'''

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值