How can I allow builtin types to subtract custom class?

Viewed 18

I have a class like this:

class Variable:

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other

And I want to be able to pass it into general functions and still allow normal operations on it.

Doing this works:

X = Variable(0)
print(X-1)  # -1

However the inverse results in a TypeError:

print(1-X)
TypeError: unsupported operand type(s) for -: 'int' and 'Variable'

Inheriting from float and using a __new__ constructor fixes that issue:

class Variable2(float):
    def __new__(cls, *args, **kwargs):
        return float.__new__(cls, args[0])

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other

x = Variable2(0)
print(1-x)  # 1.0

However when I change the value in X, the subtraction is now wrong:

x.val = 2
print(1-x)  # still #1.0

Is there a way to allow 1-x to use the internal value held by the class?

0 Answers
Related