美文网首页
六种装饰器示例

六种装饰器示例

作者: 流光汐舞 | 来源:发表于2017-07-14 20:00 被阅读0次

例1:无参数的函数

from time import ctime, sleep

def timefun(func):
    def wrappedfunc():
        print("%s called at %s"%(func.__name__, ctime()))
        func()
    return wrappedfunc

@timefun
def foo():
    print("I am foo")

foo()
sleep(2)
foo()
运行结果如下:
foo called at Fri Jul 14 19:50:18 2017
I am foo
foo called at Fri Jul 14 19:50:20 2017
I am foo

例2:被装饰的函数有参数

from time import ctime, sleep

def timefun(func):
    def wrappedfunc(a, b):
        print("%s called at %s"%(func.__name__, ctime()))
        print(a, b)
        func(a, b)
    return wrappedfunc

@timefun
def foo(a, b):
    print(a+b)

foo(3,5)
sleep(2)
foo(2,4)
运行结果如下:
foo called at Fri Jul 14 19:51:19 2017
3 5
8
foo called at Fri Jul 14 19:51:21 2017
2 4
6

例3:被装饰的函数有不定长参数

from time import ctime, sleep

def timefun(func):
    def wrappedfunc(*args, **kwargs):
        print("%s called at %s"%(func.__name__, ctime()))
        func(*args, **kwargs)
    return wrappedfunc

@timefun
def foo(a, b, c,num):
    print(a+b+c)
    print(num)

foo(3,5,7,num=10)
sleep(2)
foo(2,4,9,num=20)
运行结果如下:
foo called at Fri Jul 14 19:52:46 2017
15
10
foo called at Fri Jul 14 19:52:48 2017
15
20

例4:装饰器中的return

from time import ctime, sleep

def timefun(func):
    def wrappedfunc():
        print("%s called at %s"%(func.__name__, ctime()))
        func()
    return wrappedfunc

@timefun
def foo():
    print("I am foo")

@timefun
def getInfo():
    return '----hahah---'

foo()
sleep(2)
foo()
print(getInfo())
   执行结果:
foo called at Fri Nov  4 21:55:35 2016
I am foo
foo called at Fri Nov  4 21:55:37 2016
I am foo
getInfo called at Fri Nov  4 21:55:37 2016
None

   如果修改装饰器为return func(),则运行结果:
foo called at Fri Nov  4 21:55:57 2016
I am foo
foo called at Fri Nov  4 21:55:59 2016
I am foo
getInfo called at Fri Nov  4 21:55:59 2016
----hahah---
总结:一般情况下为了让装饰器更通用,可以有return

例5:装饰器带参数,在原有装饰器的基础上,设置外部变量

from time import ctime, sleep

def timefun_arg(pre="hello"):
    def timefun(func):
        def wrappedfunc():
            print("%s called at %s %s"%(func.__name__, ctime(), pre))
            return func()
        return wrappedfunc
    return timefun

@timefun_arg("wangcai")
def foo():
    print("I am foo")

@timefun_arg("python")
def too():
    print("I am too")

foo()
too()
运行结果如下:
foo called at Fri Jul 14 19:55:03 2017 wangcai
I am foo
too called at Fri Jul 14 19:55:03 2017 python
I am too

例6:类装饰器(扩展,非重点)

装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重写了 call() 方法,那么这个对象就是callable的。

class Test():
    def __call__(self):
        print('call me!')

t = Test()
t()  # call me
类装饰器demo

class Test(object):
    def __init__(self, func):
        print("---初始化---")
        print("func name is %s"%func.__name__)
        self.__func = func
    def __call__(self):
        print("---装饰器中的功能---")
        self.__func()

@Test
def test():
    print("----test---")
test()

说明:

  1. 当用Test来装作装饰器对test函数进行装饰的时候,首先会创建Test的实例对象,并且会把test这个函数名当做参数传递到init方法中,即在init方法中的func变量指向了test函数体

  2. test函数相当于指向了用Test创建出来的实例对象

  3. 当在使用test()进行调用时,就相当于让这个对象(),因此会调用这个对象的call方法

  4. 为了能够在call方法中调用原来test指向的函数体,所以在init方法中就需要一个实例属性来保存这个函数体的引用。
    所以才有了self.__func = func这句代码,从而在调用call方法中能够调用到test之前的函数体

运行结果如下:
---初始化---
func name is test
---装饰器中的功能---
----test---

课堂解析:

魔法方法 __call__

class Dog:
    def __call__(self):
        print('%s 被调用了'%self)

调用类对象,返回一个新的对象

Dog是Type类的一个对象,为什么Dog可以调用?
因为在Type中有call魔法。

对象如果能调用,必须所属的类有call魔法方法

Dog()

wangcai = Dog()
wangcai()

示例:

class Test(object):

    def __init__(self, func):
        print("---初始化---")
        print("func name is %s"%func.__name__)
        self.__func = func

    def __call__(self):
        print("---装饰器中的功能---")
        self.__func()

def laowang():
    print("----laowang---")

t = Test(laowang)
t()

另:

class Test(object):

    def __init__(self, func):
        print('id(self)=%s,id(func)=%s,func=%s'%(id(self),id(func),func))
        print("---初始化---")
        print("func name is %s"%func.__name__)
        self.__func = func

    def __call__(self):
        print("---装饰器中的功能---")
        return self.__func()

@Test               #laowang = Test(laowang)
def laowang():
    return "----laowang---"

print(laowang())

print(id(laowang))
print(laowang)

相关文章

网友评论

      本文标题:六种装饰器示例

      本文链接:https://www.haomeiwen.com/subject/ckmohxtx.html