【问题标题】:How can I get a class parameter from a function of class via decorator class?如何通过装饰器类从类的函数中获取类参数?
【发布时间】:2019-09-24 21:05:15
【问题描述】:

问题: 我想通过装饰器获取类的属性,这是一个类,但我不能。 问题是怎么可能?

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?

【问题讨论】:

  • 因为类,尤其是它的value 属性在装饰器执行时不存在:你不能。您只能在可调用对象中执行此操作,即在调用 bar() 时。
  • @deceze 这很有趣,我找到了解决方案。 :)

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2013-07-04
    • 1970-01-01
    • 2011-11-21
    相关资源
    最近更新 更多