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

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

个人Python环境:3.7app

在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}')

注意:spa

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

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

参考资料:get

1. Python decorators in classes博客

相关文章
相关标签/搜索