Abb*_*fei 11 python immutability
在Python中,如何重用现有的相等的不可变对象(就像这样做str)?这可以通过定义__hash__方法来完成,还是需要更复杂的措施?
Sco*_*ths 13
如果你想通过类构造函数创建并让它返回一个先前创建的对象,那么你需要提供一个__new__方法(因为当你到达__init__对象时已经创建了).
这是一个简单的示例 - 如果之前已经看到用于初始化的值,则返回先前创建的对象而不是创建的新对象:
class Cached(object):
"""Simple example of immutable object reuse."""
def __init__(self, i):
self.i = i
def __new__(cls, i, _cache={}):
try:
return _cache[i]
except KeyError:
# you must call __new__ on the base class
x = super(Cached, cls).__new__(cls)
x.__init__(i)
_cache[i] = x
return x
Run Code Online (Sandbox Code Playgroud)
请注意,对于此示例,只要可以清除,您就可以使用任何内容进行初始化.并且只是为了表明对象真正被重用:
>>> a = Cached(100)
>>> b = Cached(200)
>>> c = Cached(100)
>>> a is b
False
>>> a is c
True
Run Code Online (Sandbox Code Playgroud)