Python类中的装饰器在当前类中的声明与调用

[本文出自天外归云的博客园]

我的Python环境:3.7

在Python类里声明一个装饰器,并在这个类里调用这个装饰器。代码如下:

class Test():
    xx = False

    def __init__(self):
        pass

    def test(func):
        def wrapper(self, *args, **kwargs):
            print(self.xx)
            return func(self, *args, **kwargs)
            
        return wrapper

    @test
    def test_a(self,a,b):
        print(f'ok,{a} {b}')

注意:

1. 其中装饰器test是在类Test中声明并在其方法test_a中调用

2. 装饰器test内层wrapper函数的首参数是self

参考资料:

1. Python decorators in classes

posted @ 2018-11-14 13:35  天外归云  阅读(2764)  评论(0编辑  收藏  举报