相关疑难解决方法(0)

如何用装饰器类装饰实例方法?

考虑这个小例子:

import datetime as dt

class Timed(object):
    def __init__(self, f):
        self.func = f

    def __call__(self, *args, **kwargs):
        start = dt.datetime.now()
        ret = self.func(*args, **kwargs)
        time = dt.datetime.now() - start
        ret["time"] = time
        return ret

class Test(object):
    def __init__(self):
        super(Test, self).__init__()

    @Timed
    def decorated(self, *args, **kwargs):
        print(self)
        print(args)
        print(kwargs)
        return dict()

    def call_deco(self):
        self.decorated("Hello", world="World")

if __name__ == "__main__":
    t = Test()
    ret = t.call_deco()
Run Code Online (Sandbox Code Playgroud)

打印

Hello
()
{'world': 'World'}
Run Code Online (Sandbox Code Playgroud)

为什么self参数(应该是Test obj实例)不作为第一个参数传递给装饰函数decorated

如果我手动完成,例如:

def call_deco(self):
    self.decorated(self, "Hello", …
Run Code Online (Sandbox Code Playgroud)

python class self python-decorators

32
推荐指数
2
解决办法
1万
查看次数

标签 统计

class ×1

python ×1

python-decorators ×1

self ×1