【问题标题】:Python 3 Operator OverloadingPython 3 运算符重载
【发布时间】:2014-02-06 20:16:07
【问题描述】:

当涉及到我的类 Point 时,我正在尝试定义运算符类型 add。点正是它看起来的样子,(x, y)。我似乎无法让操作员工作,因为代码一直在打印 ma​​in.Point...>。我对这些东西很陌生,所以有人可以解释我做错了什么吗?谢谢。这是我的代码:

class Point:
def __init__(self, x=0, y=0):
    self.x = x
    self.y = y
def __add__(self, other):
    return Point(self.x + other.x, self.y + other.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)

【问题讨论】:

  • "代码不断打印<main.Point...>"。对我来说听起来很正常。你希望它打印什么?

标签: class python-3.x operator-overloading


【解决方案1】:

您的添加功能正在按预期工作。这是您的print 问题所在。你会得到像<__main__.Point object at 0x027FA5B0> 这样的丑陋结果,因为你没有告诉班级你希望它如何显示自己。实现__str____repr__ 以便它显示一个漂亮的字符串。

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return "Point({}, {})".format(self.x, self.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)

结果:

Point(8, 10)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    相关资源
    最近更新 更多