Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: subclassing tuples and operators

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.

like image 947
Jesus Martinez Garcia Avatar asked Jan 29 '26 23:01

Jesus Martinez Garcia


2 Answers

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.

like image 99
Blckknght Avatar answered Jan 31 '26 18:01

Blckknght


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
like image 21
Ivan Giuliani Avatar answered Jan 31 '26 18:01

Ivan Giuliani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!