Class point-Python

问题描述 投票:0回答:1

这些问题要求“编写一个方法add_point,该方法将作为参数提供的Point对象的位置添加到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)
?       ^  ^

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

python class point
1个回答
1
投票

您的解决方案将返回一个新的元组,而完全不修改当前对象的属性。

相反,您实际上需要按照说明更改对象的属性,并且不需要返回任何内容(即,这是“就地”操作)。

def add_point(self, other):
    self._x += other._x
    self._y += other._y
© www.soinside.com 2019 - 2024. All rights reserved.