未维护我的类对象ID

2024-06-26 11:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下要点:

class Point:
    """Two-Dimensional Point(x, y)"""
    def __init__(self, x=0, y=0):
        # Initialize the Point instance
        self.x = x
        self.y = y

    def __iter__(self):
         yield self.x
         yield self.y

    def __iadd__(self, other):
         self.x = self.x + other.x
         self.y = self.y + other.y
         return Point(self.x, self.y)
 #       return Point(self.x + other.x, self.y + other.y)

    def __add__(self, other):
         return Point(self.x + other.x, self.y + other.y)

    def __mul__(self, other):
        mulx = self.x * other
        muly = self.y * other
        return Point(mulx, muly)

    def __rmul__(self, other):
        mulx = self.x * other
        muly = self.y * other
        return Point(mulx, muly)

    @classmethod
    def from_tuple(cls, tup):
        x, y = tup
        return cls(x, y)

    def loc_from_tuple(self, tup):
  #       self.x=t[0]
  #       self.y=t[1]
        self.x, self.y = tup

    @property
    def magnitude(self):
        # """Return the magnitude of vector from (0,0) to self."""
        return math.sqrt(self.x ** 2 + self.y ** 2)

    def distance(self, self2):
         return math.sqrt((self2.x - self.x) ** 2 + (self2.y - self.y) ** 2)

    def __str__(self):
        return 'Point at ({}, {})'.format(self.x, self.y)

    def __repr__(self):
        return "Point(x={},y={})".format(self.x, self.y)

在加法过程中,我希望加法前的点的ID与加法后的相同,如下所示:

point1 = Point(2, 3)
point2 = Point(4, 5)
id1 = id(point1)
point1 += point2
print(point1)
    Point(x=6, y=8)
print(id1 == id(point1))
    True
print(point2)
    Point(x=4, y=5)

但是,当我运行此代码时,除了ID返回false之外,其他都是正确的。我的代码中是否有导致这种情况的缺陷


Tags: thefromselfreturndefpointotherprint
1条回答
网友
1楼 · 发布于 2024-06-26 11:21:57

问题出在__iadd__实现中。您应该返回self,而不是创建新对象

def __iadd__(self, other):
    self.x = self.x + other.x
    self.y = self.y + other.y
    return self

相关问题 更多 >