python复制代码会被发现吗,我发现了一个记忆代码片段,我想知道它在复制。复制...
通常,復制一個對象應該創(chuàng)建一個精確的克隆:如果它有緩存的值,也應該復制它們。如果不這樣做,這通常是對深度復制的速度優(yōu)化,不會有明顯的副作用。在
如果您正在制作某個內(nèi)容的副本,并且希望清除該副本中的緩存值,則應顯式清除該緩存。在
如果您確實希望對象的副本不復制緩存,那么定義__copy__或{}方法來控制復制。(請注意,這通常用于復制底層資源,如文件描述符和句柄)。在
這里有兩個例子。在class memoized(object):
"""
Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __copy__(self):
"""
Don't copy the cache in a copy.
"""
return memoized(self.func)
def __deepcopy__(self, memo):
"""
Don't copy the cache in a deep copy.
"""
return memoized(self.func)
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncachable for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
def __get__(self, obj, objtype):
"""Support instance methods."""
return functools.partial(self.__call__, obj)
def clear_cache(self):
self.cache = {}
@memoized
def fibonacci(n):
"Return the nth fibonacci number."
if n in (0, 1):
return n
return fibonacci(n-1) + fibonacci(n-2)
fibonacci(12)
print fibonacci.cache
fibonacci.clear_cache()
print fibonacci.cache
fibonacci(12)
print fibonacci.cache
import copy
f = copy.deepcopy(fibonacci)
print f.cache
總結(jié)
以上是生活随笔為你收集整理的python复制代码会被发现吗,我发现了一个记忆代码片段,我想知道它在复制。复制...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序功能:延时(定时)
- 下一篇: 汇编和可执行文件(Debug和Relea