如何通过装饰器类从类的函数中获取类参数?

时间:2019-05-07 08:34:46

标签: python python-3.x oop python-decorators

问题: 我想通过装饰器获得类的属性,但它不能。 问题是怎么办?

class DecoratorClass:

    def __call__(self, fn, *args, **kwargs) -> Callable:
        try:
            # do something with the TestClass value
            return fn
        finally:
            pass


class TestClass:

    def __init__(self):
        self.value = 1

    @DecoratorClass()
    def bar(self):
        return 1


如何通过DecoratorClass达到TestClass的值attr?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:)

class Decoratorclass:

    def __call__(self, fn, *args, **kwargs) -> Callable:

        def decorated(instance):
            try:
                # do something with the TestClass value
                print(instance.value)
                return fn(instance)
            finally:
                pass
        return decorated

class TestClass:

    def __init__(self):
        self.value = 1

    @Decoratorclass()
    def bar(self):
        return 1