Can you override the magic method when extending the built-in in python?

I am trying to expand strand redefine the magic method __cmp__. The following example shows that the magic method is __cmp__never called when used >:

class MyStr(str):
    def __cmp__(self, other):
        print '(was called)',
        return int(self).__cmp__(int(other))


print 'Testing that MyStr(16) > MyStr(7)'
print '---------------------------------'
print 'using _cmp__ :', MyStr(16).__cmp__(MyStr(7))
print 'using > :', MyStr(16) > MyStr(7)

when starting the results:

Testing that MyStr(16) > MyStr(7)
---------------------------------
using __cmp__ : (was called) 1
using > : False

Obviously, when used >, the basic function of “comparison” is called inside the built-in device, which in this case is alphabetized.

Is there a way to override the built- __cmp__in using magic methods? And if you cannot directly - what is going on here is different from non-magical methods, where can you?

+5
source share
1 answer

__cmp__, NotImplemented:

class MyStr(str):
    def __gt__(self, other):
        print '(was called)',
        return int(self) > int(other)


print MyStr(16) > MyStr(7)   # True

 

P.S.: , , , :

class MyStr(str):
    def __gt__(self, other):
        try:
            return int(self) > int(other)
        except ValueError:
            return False
+4

All Articles