- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do we use equivalence (“equality”) operator in Python classes?
If we use the equality operator as in the code below, we get false as output
class Integer: def __init__(self, number): self.number = number n1 = Integer(1) n2 = Integer(1) print bool(n1 == n2)
This is because Python by default uses the object identifiers for comparison operations:
To overcome this issue we must override the __eq__function
class Integer: def __init__(self, number): self.number = number def __eq__(self, other): if isinstance(self, other.__class__): return self.__dict__ == other.__dict__ return False n1 = Integer(1) n2 = Integer(1) print bool (n1 == n2) print bool (n1 != n2)
For Python 2.x, we also have to overide the __ne__function as well. This is not necessary for Python 3.x. As per documentation following holds true.
By default, __ne__() delegates to __eq__() and inverts the result unless it is NotImplemented. There are no other implied relationships among the comparison operators, for example, the truth of (x<y or x==y) does not imply x<=y.
- How do we use different CSS classes in HTML?
- Why do we use comma operator in C#?
- How can we use a diamond operator with anonymous classes in Java 9?
- How do we handle circular dependency between Python classes?
- Where do we use scope Resolution Operator (::) in C#?
- How do we use Python in interactive mode?
- How do we use Python in script mode?
- How do we use double quotation in Python?
- How can we use Python Ternary Operator Without else?
- How can we do Python operator overloading with multiple operands?
- How do we access class attributes using dot operator in Python?
- Why do we use random.seed() in Python?
- Why do we use pandas in python?
- How to use enums in Python classes?
- Why do we need inner classes in Java?