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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM