擅长:python、mysql、java
<p>这是可以做到的(假设<code>args</code>都是可散列的)</p>
<pre><code> class MyClass:
instances = {}
def __new__(cls, *args):
if args in cls.instances:
return cls.instances[args]
self = super().__new__(cls)
cls.instances[args] = self
return self
a = MyClass('hello')
b = MyClass('hello')
c = MyClass('world')
a is b and a == b and a is not c and a != c # True
</code></pre>
<hr/>
<p><code>is</code>是显示两个对象是同一实例的python操作符。<code>==</code>在对象上回退到<code>is</code>,在对象上它没有被覆盖。你知道吗</p>
<hr/>
<p>正如在评论中指出的,如果你有副作用的<code>__init__</code>,这可能会有点麻烦。下面是一个可以避免这种情况的实现:</p>
<pre><code>class Coord:
num_unique_instances = 0
_instances = {}
def __new__(cls, x, y):
if (x, y) in cls._instances:
return cls._instances[x, y]
self = super().__new__(cls)
# __init__ logic goes here will only run once
self.x = x
self.y = y
cls.num_unique_instances += 1
# __init__ logic ends here
cls._instances[x, y] = self
return self
# no __init__ method
</code></pre>