我正在尝试在类中的某些方法上实现装饰器,以便如果尚未计算该值,则该方法将计算该值,否则它将仅返回存储在实例中的预计算值defaultdict
。我似乎无法弄清楚如何defaultdict
从类外部声明的装饰器内部访问实例。关于如何实现这一点的任何想法?
以下是导入(作为一个工作示例):
from collections import defaultdict
from math import sqrt
这是我的装饰器:
class CalcOrPass:
def __init__(self, func):
self.f = func
#if the value is already in the instance dict from SimpleData,
#don't recalculate the values, instead return the value from the dict
def __call__(self, *args, **kwargs):
# can't figure out how to access/pass dict_from_SimpleData to here :(
res = dict_from_SimpleData[self.f.__name__]
if not res:
res = self.f(*args, **kwargs)
dict_from_SimpleData[self.f__name__] = res
return res
这是带有修饰方法的 SimpleData 类:
class SimpleData:
def __init__(self, data):
self.data = data
self.stats = defaultdict() #here's the dict I'm trying to access
@CalcOrPass
def mean(self):
return sum(self.data)/float(len(self.data))
@CalcOrPass
def se(self):
return [i - self.mean() for i in self.data]
@CalcOrPass
def variance(self):
return sum(i**2 for i in self.se()) / float(len(self.data) - 1)
@CalcOrPass
def stdev(self):
return sqrt(self.variance())
到目前为止,我已经尝试在SimpleData 中声明装饰器,尝试使用装饰器传递多个参数(显然你不能这样做),并在我的转椅上旋转,同时试图将纸飞机扔进我的蝎子坦克。任何帮助,将不胜感激!