【问题标题】:One decorator for class and method一个类和方法的装饰器
【发布时间】:2015-12-08 09:30:15
【问题描述】:

是否有可能制作一个我可以申请类和方法的装饰器?

例子:

@my_dec(1)
class MyClass(object):
    @my_dec(2)
    def my_method(self):
        # something here

assert MyClass._x == 1
assert MyCLass.my_method._x == 2

【问题讨论】:

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


    【解决方案1】:

    是的,这是可能的。基本上,您需要创建一个接受值 1 或 2 的函数,然后返回函数或类对象稍后传递给的实际装饰器,现在在装饰器内部,我们可以使用 setattr 设置类的属性或函数对象。

    def my_dec(x):
        # Here x is going to be the argument passed to my_dec, i.e 1 or 2 
        def decorator(func_or_cls):
            setattr(func_or_cls, '_x', x)
            return func_or_cls
        return decorator
    
    @my_dec(1)
    class MyClass(object):
        @my_dec(2)
        def my_method(self):
            pass
    
    assert MyClass._x == 1
    assert MyClass.my_method._x == 2
    

    要了解装饰器的工作原理,请阅读这个很棒的答案:How can I make a chain of function decorators in Python?

    【讨论】:

    • 谢谢,太简单了。 :)
    猜你喜欢
    • 1970-01-01
    • 2012-09-11
    • 2014-01-14
    • 2020-01-11
    • 2014-04-08
    • 2021-10-23
    • 1970-01-01
    • 2011-10-05
    • 2016-07-04
    相关资源
    最近更新 更多