Assume I have a class A with a overriden hash method that returns some user-defined integer:
class A:
def __init__(self,hash):
self.hash = hash
def __hash__(self):
return self.hash
def __cmp__(self,other):
return cmp(self.hash,other.hash)
Now, at any given point in time, I'd like to have only one object with the same hash, so I maintain a set s
that contains such objects of class A. My problem is the following:
s = {A(1234)}
a = A(1234)
if a in s:
# then assign the corresponding object in set s to a
How can I achieve this?
Thanks!
Don't use a set, use a dictionary (which is also a set, in a sense).
objects = {}
a = A(1234)
if a.hash in objects:
a = objects[a.hash]
objects[a.hash] = a
I'd use a singleton implemented as a class variable:
>>> class A:
HASH = 0
def __init__(self):
self.hash = A.HASH
A.HASH += 1
def __hash__(self):
return self.hash
def __cmp__(self,other):
return cmp(self.hash, other.hash)
>>> a = A()
>>> a.__hash__()
0
>>> a2 = A()
>>> a2.__hash__()
1
>>>
Since it's increased each time you instanciate a new object, you're sure not to have twice the same value (this might not be thread-safe, though).
EDIT : if the hash value is computed, this solution is not valid since it starts from 0 arbitrarily...
I used the following mechanism to make sure that no duplicate object was ever created. This is a mixture of Emmanuel's and Jordan's answers.
class A(object):
__singletons__ = dict()
def __new__(cls,hash):
if hash not in cls.__singletons__.keys():
cls.__singletons__[hash] = super(A,cls).__new__(cls)
return cls.__singletons__[hash]
def __init__(self,hash):
self.hash = hash
def __hash__(self):
return self.hash
def __cmp__(self,other):
return cmp(self.hash,other.hash)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.