Reputation: 873
class A():
def __init__(self, fn):
self.fn = fn
a1 = A('a')
a2 = A('a')
b = A('b')
print (a1==a2)
print (a1==b)
result should be True for first but False for second. I knew some way to implement singleton in Python. But all of them only generate one instance for every call. How do we link the __new__ method to __init__?
Upvotes: 1
Views: 502
Reputation: 3158
It is not a singleton you're looking for.
A singleton is when your class can produce only one instance at the time, so that you will have A('a') is A('b')
True.
What can be deduced from your example is you're looking to define __eq__
, which has been explained here.
Note that if you want to test equality for custom objects, you may have to define __hash__
, which is explained here
Upvotes: 0
Reputation: 600059
There is no reason to think about singletons here and no reason to do anything with __new__
. If you want two instances to be considered equal based on some condition, then you need to define __eq__
.
def __eq__(self, other):
return isinstance(other, A) and self.fn == other.fn
(Note, fn
is usually used as a holder for functions; you should think of another attribute name.)
Upvotes: 3