I'd like to be able to have the operator of my class interact with regular types in a way that I define. Lets say, for example, I have:
class Mynum(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other.x
a = Mynum(1)
b = Mynum(2)
print a+b
This works just fine, but now if I try to do:
print a+2
I get an error since an int
does not have a member named x
. How do I define Mynum
+ int
in the class? This sounds like a job for decorators or metaclasses, but I'm terribly unfamiliar with their usage. This question seems similar, but not quite identical.
Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.
A very popular and convenient example is the Addition (+) operator. Just think how the '+' operator operates on two numbers and the same operator operates on two strings. It performs “Addition” on numbers whereas it performs “Concatenation” on strings.
Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.
def __add__(self, other):
if isinstance(other, self.__class__):
return self.x + other.x
elif isinstance(other, int):
return self.x + other
else:
raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))
class Mynum(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
try:
return self.x + other.x
except AttributeError:
return self.x + other
__radd__=__add__
a = Mynum(1)
b = Mynum(2)
print(a+b)
# 3
print(a+2)
# 3
print(2+a)
# 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With