Python:运算符重载特定类型 [英] Python : Operator Overloading a specific type
本文介绍了Python:运算符重载特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够让我的类的操作符以我定义的方式与常规类型交互.比如说,我有:
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
我收到一个错误,因为 int
没有名为 x
的成员.如何在类中定义 Mynum
+ int
?这听起来像是装饰器或元类的工作,但我非常不熟悉它们的用法.这个问题看似相似,但并不完全相同.>
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))
这篇关于Python:运算符重载特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文