未保存对象的ID

时间:2018-08-18 23:07:50

标签: python python-3.x

我开设了以下课程:

  import math

    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 __add__(self, other):
            addedx = self.x + other.x
            addedy = self.y + other.y
            return Point(addedx, addedy)

        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, 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。

1 个答案:

答案 0 :(得分:0)

id基本上是内存地址。如果创建一个新对象,则它可能具有不同的ID。如果出于某种原因想要可变的Point对象,请考虑使用__iadd__ (and friends) methods,它可以就地进行更新。

相关问题