Python:重载特定类型的运算符

发布于 2024-09-08 06:07:33 字数 557 浏览 1 评论 0原文

我希望能够让我的类的运算符以我定义的方式与常规类型进行交互。比方说,我有:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七婞 2024-09-15 06:07:33
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))
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))
梦过后 2024-09-15 06:07:33
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
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
静若繁花 2024-09-15 06:07:33

为什么要使用额外的切换和/或异常处理?使用以下方法将是一种更简单的方法:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文