[Python] Inconsistent Behavior of Addition between int and float

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I make a class that takes a number during instantiation. It only has one instance attribute, that is self.value. This class also has some methods such as __add__ and __radd__ that are proxies of the original methods. If self.value holds a float object, all these methods work well, but they raise error if self.value holds an integer object and operate with a float value. Here is my code.

    class MyNumber:
    def __init__(self, value):
    self.value = value
    def __repr__(self):
    return f'{self.__class__.__name__}(value={self.value})'
    def __int__(self):
    return self.value.__int__()
    def __float__(self):
    return self.value.__float__()
    def __bool__(self):
    return self.value.__bool__()
    def __add__(self, other):
    return self.value.__add__(other)
    def __radd__(self, other):
    return self.value.__radd__(other)


    Here I test my code.

    mynumber_int = MyNumber(1)
    print(mynumber_int)
    print(mynumber_int + 2) # works as expected
    print(3 + mynumber_int) # works as expected
    #print(mynumber_int + 2.) # TypeError: unsupported operand type(s) for +: 'MyNumber' and 'float'
    #print(3. + mynumber_int) # TypeError: unsupported operand type(s) for +: 'float' and 'MyNumber'

    mynumber_float = MyNumber(1.)
    print(mynumber_float)
    print(mynumber_float + 2) # works as expected
    print(3 + mynumber_float) # works as expected
    print(mynumber_float + 2.) # works as expected
    print(3. + mynumber_float) # works as expected


    I think mynumber_int + 2. works like 3 + mynumber_float, unfortunately the first one raises error and the second one succeeds. For any explanation and help, I very appericate.

    Continue reading...

Compartilhe esta Página