python - 默认内存所有方法

标签 python immutability

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

我想通过大量内存对频谱执行计算的函数来利用这一点。这是一个玩具示例:

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/

相关文章:

ruby - 使用 define_singleton_method 创建的赋值方法返回错误值

scala - 关于Scala变量可变性的问题

python - Flask:缓存静态文件(.js、.css)

python - 如何将二维数组拆分为较小的可变大小的二维数组?

python - 如何将大小为 3 的元组列表制作为键值对?

properties - 我如何使用 NDepend 找到哪些属性 getter 有副作用?

c# - 为什么 IEnumerable<T> 中的元素有时是可变的,有时是不可变的?

python - 从脚本获取与从 python shell 获取不同的电影信息

python - 如何将 shell 命令输出重定向到 Python 脚本输入?

python - 在Python中的线程之间共享字典时是否可以避免锁定开销?