我正在编写一个应用程序,用于收集和显示来自科学仪器的数据。其中一条数据是一个频谱:本质上只是一个值列表,加上一个包含一些元数据的字典。一旦应用程序收集了数据,它就不会改变,因此列表和元数据都可以被认为是不可变的。
我想通过大量内存对频谱执行计算的函数来利用这一点。这是一个玩具示例:
class Spectrum(object):
def __init__(self, values, metadata):
self.values = values
self.metadata = metadata
# self.values and self.metadata should not change after this point.
@property
def first_value(self):
return self.values[0]
def multiply_by_constant(self, c):
return [c*x for x in self.values]
def double(self):
return self.multiply_by_constant(2)
我想要的是默认情况下对这些方法中的每一个进行内存。有什么方法(元类?)可以在不复制的情况下完成此操作 one of these memoization decorators到处写@memoize
?
最佳答案
我继续写了一个元类来解决你的问题。它遍历所有属性并检查它们是否可调用(通常是函数、方法或类)并装饰那些是可调用的。当然,您会将 decorator
设置为您的内存装饰器(例如 functools.lru_cache
)。
如果您只想装饰方法,而不是任何可调用的,您可以用检查替换测试
。但它可能会在未来引入一个错误,你不记得它只适用于方法,并添加一个函数或类,这不会被内存!hasattr(val, "__call__")
。 ismethod(val)
参见 this关于 Python 中元类的更多信息的问题。
def decorate(f):
def wrap(*args, **kwargs):
# Print a greeting every time decorated function is called
print "Hi from wrap!"
return f(*args, **kwargs)
return wrap
class DecorateMeta(type):
def __new__(cls, name, bases, dct):
# Find which decorator to use through the decorator attribute
try:
decorator = dct["decorator"]
except KeyError:
raise TypeError("Must supply a decorator")
# Loop over all attributes
for key, val in dct.items():
# If attribute is callable and is not the decorator being used
if hasattr(val, "__call__") and val is not decorator:
dct[key] = decorator(val)
return type.__new__(cls, name, bases, dct)
class Test:
__metaclass__ = DecorateMeta
decorator = decorate
def seasonal_greeting(self):
print "Happy new year!"
Test().seasonal_greeting()
# Hi from wrap!
# Happy new year!
关于python - 默认内存所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20791246/