Search code examples
pythonpython-3.xooppython-decorators

How can I get a class parameter from a function of class via decorator class?


The problem: I want to get an attribute of class via decorator which is a class but I can not. The question is how can?

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


How can I reach the the TestClass's value attr via DecoratorClass?


Solution

  • I got the solution :)

    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