Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 理解这个记忆装饰器_Python - Fatal编程技术网

Python 理解这个记忆装饰器

Python 理解这个记忆装饰器,python,Python,我很难理解这个备忘录装饰 def method(func): """ Decorator for caching parameterless bound method """ key = '_memoize_%s' % func.__name__ @wraps(func) def wrapper(self): if not hasattr(self, key): setattr(self, key, func

我很难理解这个备忘录装饰

def method(func):
    """
    Decorator for caching parameterless bound method
    """
    key = '_memoize_%s' % func.__name__
    @wraps(func)
    def wrapper(self):
        if not hasattr(self, key):
            setattr(self, key, func(self))
        return getattr(self, key)

    return wrapper
假设我有:

@method
def add(x,y):
    return x+y

是否将键
\u memoize\u add
附加到元组(x,y),因为这是传递给包装器的内容。

装饰器将方法的返回值存储为私有属性。因此,它只适用于类实例,而不适用于普通函数

decorator的
func
参数是它正在包装的方法,返回的
wrapper
函数将被调用,而不是方法。调用包装器时,其
self
参数将是类的实例,因此
settattr
调用将
func
的结果缓存为一个由
key
命名的私有属性。之后,所有进一步的调用将返回
键的缓存值

下面是一个简单的测试,展示了如何使用它:

import random
from functools import wraps

def method(func):
    key = '_memoize_%s' % func.__name__
    @wraps(func)
    def wrapper(self):
        if not hasattr(self, key):
            setattr(self, key, func(self))
        return getattr(self, key)

    return wrapper

class Test(object):
    @method
    def cached(self):
        return random.random()

    def uncached(self):
        return random.random()

t = Test()
for x in range(3):
    print('cached: %s' % t.cached())
    print('uncached: %s' % t.uncached())
print(t.__dict__)
输出:

cached: 0.6594806157188309
uncached: 0.2492466307551897
cached: 0.6594806157188309
uncached: 0.08718572660830726
cached: 0.6594806157188309
uncached: 0.5501638352647334
{'_memoize_cached': 0.6594806157188309}

你在哪里找到这个装饰师的?有关备忘录,请参见@shx2 no,我在brosing here@Griffosx时找到的,我在这里浏览网站的源代码时发现的: