1
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__?

2
  • 1
    Do you want a1 and a2 to be separate but equal objects? Commented Aug 1, 2017 at 21:19
  • define def __eq__(self,other): return self.fn == other.fn and the == operator is redefined to match your needs. Commented Aug 1, 2017 at 21:19

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

I was going to answer that (except for the isinstance part). Maybe you should add that the == should be redefined if fn and self.fn can be 2 different class instances bearing the same values (and on, and on)
also isinstance(other, A) should probably be type(other) == A to restrict to actual A objects, not children
Thank you for you help. How about if I want to make a1 is a2 equal True?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.