equality

Compare object instances for equality by their attributes

Compare object instances for equality by their attributes Question: I have a class MyClass, which contains two member variables foo and bar: class MyClass: def __init__(self, foo, bar): self.foo = foo self.bar = bar I have two instances of this class, each of which has identical values for foo and bar: x = MyClass(‘foo’, ‘bar’) …

Total answers: 16

Elegant ways to support equivalence ("equality") in Python classes

Elegant ways to support equivalence ("equality") in Python classes Question: When writing custom classes it is often important to allow equivalence by means of the == and != operators. In Python, this is made possible by implementing the __eq__ and __ne__ special methods, respectively. The easiest way I’ve found to do this is the following …

Total answers: 11

Is there a difference between "==" and "is"?

Is there a difference between "==" and "is"? Question: My Google-fu has failed me. In Python, are the following two tests for equality equivalent? n = 5 # Test one. if n == 5: print ‘Yay!’ # Test two. if n is 5: print ‘Yay!’ Does this hold true for objects where you would be …

Total answers: 14