【问题标题】:decorate a python function with a method from a class object用类对象中的方法装饰 python 函数
【发布时间】:2017-03-13 21:05:36
【问题描述】:

我希望在函数上使用装饰器。问题是装饰器函数是在一个类中定义的,它必须特定于该类的一个对象。例如:

class Foo:
    def __init__(self):
        self.a = 1

    def set_a(self, val):
        self.a = val

    def bar(func):
        def _args(*args, **kwargs):
            func(*args, **kwargs) + self.a
        return _args

if __name__ == "__main__":

    foo = Foo()
    foo2 = Foo()

    foo.set_a = 2

    @foo.bar
    def multip(a, b):
        return a * b

    multip(1, 2)  # here i would expect answer to be 4        

    foo.set_a = 3

    multip(1, 2)  # here i would expect answer to be 5

    @foo2.bar
    def multip2(a, b):
        return a * b

    multip2(1, 2)  # here i would expect the answer to be 3

【问题讨论】:

  • “特定于该类的对象”是什么意思?您已经拥有的代码和您想要拥有的代码之间有什么区别? (请注意,您忘记了 bar 上的 self 参数。)

标签: python class decorator


【解决方案1】:

所以你可以做你想要的,但我不确定我是否会认为这是一个好的装饰器。为什么不直接使用类装饰器并使用__init__()__call__()

无论如何,这是您的固定代码:

class Foo:
    def __init__(self, a=1):
        self.a = a

    def bar(self, func):
#           ^^^^ you need self
        def _args(*args, **kwargs):
            return func(*args, **kwargs) + self.a
#           ^^^^^^ You need to return here.
    return _args

foo = Foo()

@foo.bar
def multip(a, b):
    return a * b

multip(1, 2)
# 3
foo.a = 2
multip(1, 2)
# 4
foo.a = 3
multip(1, 2)
# 5

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2021-04-16
    • 2013-01-19
    • 2016-07-04
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多