decorators#
类#
函数#
|
装饰器,使方法将其结果缓存在 self 中,以便每个 |
|
清除给定对象的已记忆方法或 @memoizedproperty 结果 |
|
装饰器,使方法将其结果缓存在 self 中,以便每个 |
- memoizemethod(method)#
装饰器,使方法将其结果缓存在 self 中,以便每个输入组合,并在后续调用中返回缓存的结果。不支持命名参数或不可哈希的 arg 值。
>>> class Foo (object): ... @memoizemethod ... def foo(self, x, y=0): ... print('running method with', x, y) ... return x + y + 3 ... >>> foo1 = Foo() >>> foo2 = Foo() >>> foo1.foo(10) running method with 10 0 13 >>> foo1.foo(10) 13 >>> foo2.foo(11, y=7) running method with 11 7 21 >>> foo2.foo(11) running method with 11 0 14 >>> foo2.foo(11, y=7) 21 >>> class Foo (object): ... def __init__(self, lower): ... self.lower = lower ... @memoizemethod ... def range_tuple(self, upper): ... print('running function') ... return tuple(i for i in range(self.lower, upper)) ... @memoizemethod ... def range_iter(self, upper): ... print('running function') ... return (i for i in range(self.lower, upper)) ... >>> foo = Foo(3) >>> foo.range_tuple(6) running function (3, 4, 5) >>> foo.range_tuple(7) running function (3, 4, 5, 6) >>> foo.range_tuple(6) (3, 4, 5) >>> foo.range_iter(6) Traceback (most recent call last): TypeError: Can't memoize a generator or non-hashable object!
- clear_memoized_methods(obj, *method_names)#
清除给定对象中给定方法名称的已记忆方法或 @memoizedproperty 结果。
>>> v = [0] >>> def inc(): ... v[0] += 1 ... return v[0] ... >>> class Foo(object): ... @memoizemethod ... def foo(self): ... return inc() ... @memoizedproperty ... def g(self): ... return inc() ... >>> f = Foo() >>> f.foo(), f.foo() (1, 1) >>> clear_memoized_methods(f, 'foo') >>> (f.foo(), f.foo(), f.g, f.g) (2, 2, 3, 3) >>> (f.foo(), f.foo(), f.g, f.g) (2, 2, 3, 3) >>> clear_memoized_methods(f, 'g', 'no_problem_if_undefined') >>> f.g, f.foo(), f.g (4, 2, 4) >>> f.foo() 2
- memoizedproperty(func)#
装饰器,使方法将其结果缓存在 self 中,以便每个输入组合,并在后续调用中返回缓存的结果。不支持命名参数或不可哈希的 arg 值。
>>> class Foo (object): ... _x = 1 ... @memoizedproperty ... def foo(self): ... self._x += 1 ... print('updating and returning {0}'.format(self._x)) ... return self._x ... >>> foo1 = Foo() >>> foo2 = Foo() >>> foo1.foo updating and returning 2 2 >>> foo1.foo 2 >>> foo2.foo updating and returning 2 2 >>> foo1.foo 2