Python:重载特定类型的运算符
我希望能够让我的类的运算符以我定义的方式与常规类型进行交互。比方说,我有:
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
这工作得很好,但现在如果我尝试这样做:
print a+2
我收到一个错误,因为 int
没有名为 x
的成员。如何在类中定义 Mynum
+ int
?这听起来像是装饰器或元类的工作,但我对它们的用法非常不熟悉。 这个问题看起来很相似,但不完全相同。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么要使用额外的切换和/或异常处理?使用以下方法将是一种更简单的方法:
Why use the extra switching and/or exception handling? Using the following would be a simpler approach: