Decorator class 装饰一个 class 方法
Decorator class decorating a class method
我有一个装饰器,我将其实现为 class:
class Cached(object):
def __init__(self, func):
self.cache = None
self.func = func
def __call__(self, *args, **kwargs):
if self.cache is None or (time.time() - self.cache[0] >= 1000):
res = self.f(*args, **kwargs)
self.cache = (time.time(), res)
else:
res = self.cache[1]
return res
我想用这个装饰器装饰一个class的方法,例如:
class Foo(object):
def __init__(self, x):
self.x = x
@cached
def bar(self, y):
return self.x + y
就目前而言,
f = Foo(10)
f.bar(11)
投掷 TypeError: foo() takes exactly 2 arguments (1 given)
。 f.bar(f, 11)
有效,但代码气味相当于纽约市环卫工人罢工期间的夏天。我错过了什么?
ETA:最初,我试图将缓存实现为一个函数:
def cached(cache):
def w1(func):
def w2(*args, **kwargs):
# same
return w2
return w1
但我不断收到有关 cache
在定义之前被使用的奇怪范围界定错误,切换到装饰器 class 已修复。
您需要将此添加到装饰器中 class:
def __get__(self, obj, objtype):
"""support instance methods"""
from functools import partial
return partial(self.__call__, obj)
我有一个装饰器,我将其实现为 class:
class Cached(object):
def __init__(self, func):
self.cache = None
self.func = func
def __call__(self, *args, **kwargs):
if self.cache is None or (time.time() - self.cache[0] >= 1000):
res = self.f(*args, **kwargs)
self.cache = (time.time(), res)
else:
res = self.cache[1]
return res
我想用这个装饰器装饰一个class的方法,例如:
class Foo(object):
def __init__(self, x):
self.x = x
@cached
def bar(self, y):
return self.x + y
就目前而言,
f = Foo(10)
f.bar(11)
投掷 TypeError: foo() takes exactly 2 arguments (1 given)
。 f.bar(f, 11)
有效,但代码气味相当于纽约市环卫工人罢工期间的夏天。我错过了什么?
ETA:最初,我试图将缓存实现为一个函数:
def cached(cache):
def w1(func):
def w2(*args, **kwargs):
# same
return w2
return w1
但我不断收到有关 cache
在定义之前被使用的奇怪范围界定错误,切换到装饰器 class 已修复。
您需要将此添加到装饰器中 class:
def __get__(self, obj, objtype):
"""support instance methods"""
from functools import partial
return partial(self.__call__, obj)