Python : Operator Overloading a specific type
I'd like to be able to ha开发者_运维技巧ve 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.
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
Why use the extra switching and/or exception handling? Using the following would be a simpler approach:
class MyNum(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
return other + self.x
__radd__ = __add__
x = MyNum(5)
y = MyNum(6)
print x + 2
7
print 2 + x
7
print x + y
11
print y + x
11
精彩评论