默认所有方法缓存

2024-05-16 18:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个应用程序来收集和显示科学仪器的数据。数据的一部分是频谱:本质上只是一个值列表,外加一个包含一些元数据的字典。一旦应用程序收集了数据,它就不会改变,所以列表和元数据都可以被认为是不可变的。在

我想利用这一点,通过大量地记忆执行频谱计算的函数。下面是一个玩具的例子:

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的情况下完成这项工作?在


Tags: 数据方法self应用程序列表byreturndef
2条回答

我把fridge的回答改为:

from inspect import isfunction

class Immutable(type):
    def __new__(cls, name, bases, dct):
        for key, val in dct.items():
            # Look only at methods/functions; ignore those with
            # "special" names (starting with an underscore)
            if isfunction(val) and val.__name__[0] != '_':
                dct[key] = memoized(val)
        return type.__new__(cls, name, bases, dct)

decorator是提前知道的,所以我不需要在对象本身中指定它。我也只关心方法,尽管由于我还不明白的原因,当Immutable.__new__看到它们时,对象的所有方法都是未绑定的,因此它们是函数,而不是方法。我还排除了名称以下划线开头的方法:在记忆的情况下,您不希望对__init__或{}之类的方法做任何操作。在

我继续写了一个元类来解决你的问题。它遍历所有属性并检查它们是否可调用(通常是函数、方法或类),并修饰那些可调用的属性。当然,您可以将decorator设置为您的记忆装饰器(例如functools.lru_cache)。在

如果您只想修饰方法,而不是任何可调用的方法,那么可以将测试hasattr(val, "__call__")替换为inspect.ismethod(val)。但它可能会在将来引入一个bug,你不记得它只适用于方法,并添加了一个函数或类,而这些都不会被记住!在

有关Python中元类的更多信息,请参见thisSO question。在

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!

相关问题 更多 >