Class 点 - Python

Class point - Python

问题问到"Write a method add_point that adds the position of the Point object given as an argument to the position of self"。到目前为止我的代码是这样的:

import math
epsilon = 1e-5

class Point(object):
    """A 2D point in the cartesian plane"""
    def __init__(self, x, y):
        """
        Construct a point object given the x and y coordinates

        Parameters:
            x (float): x coordinate in the 2D cartesian plane
            y (float): y coordinate in the 2D cartesian plane
        """
        self._x = x
        self._y = y

    def __repr__(self):
        return 'Point({}, {})'.format(self._x, self._y)

    def dist_to_point(self, other):
        changex = self._x - other._x
        changey = self._y - other._y
        return math.sqrt(changex**2 + changey**2)

    def is_near(self, other):
        changex = self._x - other._x
        changey = self._y - other._y
        distance =  math.sqrt(changex**2 + changey**2)
        if distance < epsilon:
            return True

    def add_point(self, other):
        new_x = self._x + other._x
        new_y = self._y + other._y
        new_point = new_x, new_y
        return new_point

但是,我收到此错误消息:

Input: pt1 = Point(1, 2)
--------- Test 10 ---------
Expected Output: pt2 = Point(3, 4)
Test Result: 'Point(1, 2)' != 'Point(4, 6)'
- Point(1, 2)
?       ^  ^
+ Point(4, 6)
?       ^  ^

所以我想知道我的代码有什么问题?

您的解决方案return是一个新的元组,根本不修改当前对象的属性。

相反,您需要根据说明实际更改对象的属性,不需要 return 任何操作(即,这是一个 "in-place" 操作)。

def add_point(self, other):
    self._x += other._x
    self._y += other._y