添加适用于点对象或元组的方法

发布于 2024-12-09 04:23:14 字数 1053 浏览 0 评论 0原文

我的一个练习是为 Points 编写一个与 Point 对象或元组一起使用的 add 方法:

  • 如果第二个操作数是 Point,该方法应该返回一个新的 Point,其 x 坐标是操作数的 x 坐标之和,y 坐标也是如此。
  • 如果第二个操作数是元组,则该方法应将元组的第一个元素添加到 x 坐标,将第二个元素添加到 y 坐标,并返回一个新的 Point 和结果。

这就是我已经走了多远,我不确定我的代码的元组部分是否准确。有人可以阐明我如何为元组部分调用这个程序吗?我想我已经完成了第一部分。

这是我的代码:

Class Point():
    def__add__(self,other):
            if isinstance(other,Point):
                    return self.add_point(other)
            else:
                    return self.print_point(other)

    def add_point(self,other):
            totalx = self.x + other.x
            totaly = self.y + other.y
            total = ('%d, %d') % (totalx, totaly)
            return total

    def print_point(self):
            print ('%d, %d) % (self.x, self.y)

    blank = Point()
    blank.x = 3
    blank.y = 5
    blank1 = Point()
    blank1.x = 5
    blank1.y = 6

这是我到目前为止构建的代码,我不确定如何使用元组部分实际运行它。我知道如果它执行了 blank + Blank1 if 部分将运行并调用 add_point 函数,但我如何启动元组。我不确定我写得是否正确......请帮忙。

One of my exercises says to write an add method for Points that works with either a Point object or a tuple:

  • If the second operand is a Point, the method should return a new Point whose x coordinate is the sum of the x coordinates of the operands, and likewise for the y coordinates.
  • If the second operand is a tuple, the method should add the first element of the tuple to the x coordinate and the second element to the y coordinate, and return a new Point with the result.

This how far I got and I'm not sure if the tuple portion of my code is accurate. Can someone shed some light how I would call this program for the tuple portion. I think I nailed the first part.

Here is my code:

Class Point():
    def__add__(self,other):
            if isinstance(other,Point):
                    return self.add_point(other)
            else:
                    return self.print_point(other)

    def add_point(self,other):
            totalx = self.x + other.x
            totaly = self.y + other.y
            total = ('%d, %d') % (totalx, totaly)
            return total

    def print_point(self):
            print ('%d, %d) % (self.x, self.y)

    blank = Point()
    blank.x = 3
    blank.y = 5
    blank1 = Point()
    blank1.x = 5
    blank1.y = 6

That's what I've built so far and I'm not sure how to actually run this with the tuple part. I know if it did blank + blank1 the if portion would run and call the add_point function but how do I initiate the tuple. I'm not sure if I wrote this correctly... please assist.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

爱*していゐ 2024-12-16 04:23:14

您可以简单地从元组派生您的类(或者仅实现__getitem__)。

class Point(tuple):
    def __new__(cls, x, y):
        return tuple.__new__(cls, (x, y))

    def __add__(self, other):
        return Point(self[0] + other[0], self[1] + other[1])

    def __repr__(self):
        return 'Point({0}, {1})'.format(self[0], self[1])

p = Point(1, 1)
print p + Point(5, 5) # Point(6, 6)
print p + (5, 5)      # Point(6, 6)

You can simply derive your class from the tuple (or just implement __getitem__).

class Point(tuple):
    def __new__(cls, x, y):
        return tuple.__new__(cls, (x, y))

    def __add__(self, other):
        return Point(self[0] + other[0], self[1] + other[1])

    def __repr__(self):
        return 'Point({0}, {1})'.format(self[0], self[1])

p = Point(1, 1)
print p + Point(5, 5) # Point(6, 6)
print p + (5, 5)      # Point(6, 6)
歌枕肩 2024-12-16 04:23:14

或者,如果您希望能够使用 point.x 和 point.y 语法,您可以实现以下内容:

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other): 
        if isinstance(other, Point):
            return Point(self.x + other.x, self.y + other.y)
        elif isinstance(other, tuple):
            return Point(self.x + other[0], self.y + other[1])
        else:
            raise TypeError("unsupported operand type(s) for +: 'Point' and '{0}'".format(type(other)))

    def __repr__(self):
        return u'Point ({0}, {1})'.format(self.x, self.y) #Remove the u if you're using Python 3

Alternatively, if you want to be able to use point.x and point.y syntax, you could implement the following:

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other): 
        if isinstance(other, Point):
            return Point(self.x + other.x, self.y + other.y)
        elif isinstance(other, tuple):
            return Point(self.x + other[0], self.y + other[1])
        else:
            raise TypeError("unsupported operand type(s) for +: 'Point' and '{0}'".format(type(other)))

    def __repr__(self):
        return u'Point ({0}, {1})'.format(self.x, self.y) #Remove the u if you're using Python 3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文