How would I be able to use a
/-
operator on a class object when there is no actual value that I am adding or subtracting from?
I would assume that the actual value is 0 from a sample code:
x = 2.5
print( x)
print(-x)
print(0-x)
>>> 2.5
>>> -2.5
>>> -2.5
However, when doing this on my class Interval on its __add__
and __radd__
method and trying to account for a nonexistent or 0? value, I get the TypeError: bad operand type for unary : 'Interval'
class Interval:
def __init__(self, mini, maxi):
self.mini = mini
self.maxi = maxi
def __add__(self, other):
if isinstance(other,(int,float)):
mini_sum = self.mini other
maxi_sum = self.maxi other
return Interval(mini_sum, maxi_sum)
elif isinstance(other, Interval):
mini_sum = self.mini other.mini
maxi_sum = self.maxi other.maxi
return Interval(mini_sum, maxi_sum)
elif other == 0 or None:
return Interval(self.mini, self.maxi)
else:
raise TypeError('Value to add must be an int, float, or Interval class object')
if __name__ == '__main__':
x = Interval(2.5,3.0)
print( x)
>>> TypeError: bad operand type for unary : 'Interval'
My __add__
and __radd__
have the same code, so I've only included __add__
to keep the post shorter.
Am I handling this with the wrong method? I assumed x
would use the __add__
method, but perhaps I am wrong here?
CodePudding user response:
The unary
and -
operators use the __pos__()
and __neg__()
special methods.
(I wanted to give a better example than this but I'm being called away. This should illustrate the idea. Just like using __add__()
, et al, you'd want to create and return a new object with the correct value)
As an example:
class Foo:
def __neg__(self):
return "I'm a negative Foo!"
def __pos__(self):
return "I'm a positive Foo!"
>>> f = Foo()
>>> f
I'm a positive Foo!"
>>> -f
I'm a negative Foo!"