I am subclassing tuple. I want to override the equal method. It doesn't seem to be working. This is my minimum working example:
class OPS(tuple):
def __new__(self, data):
self=tuple(data)
return self
def __eq__(A,B):
print 'Hi'
return True
O1=OPS([1,2,3])
O2=OPS([1,2,4])
O1==O2
It returns False, when it should be printing 'Hi' and then returning True. Any ideas on what I am doing wrong? I bet it is quite stupid, but I am at loss.
The issue is in your __new__ method is creating your objects. You're returning regular tuple instances, not instances of your subclass, so the __eq__ method you've written will never be called.
Try changing __new__ to:
def __new__(cls, data):
self = super(OPS, cls).__new__(cls, data)
return self
The self value returned by this version will be an OPS instance.
You are returning a tuple instance in __new__, not an instance of OPS. You can however skip overriding __new__ in this case since you're not altering the input parameters (in which case __new__ would be needed since tuple is an immutable type). This works as expected, for example:
class OPS(tuple):
def __eq__(self, other):
return True
o1 = OPS([1,2,3])
o2 = OPS([1,2,4])
print o1 == o2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With