Question: Hi, This is probably a really silly question, but I'm struggling to understand a part of my Python practice problem. I have code that works,

Hi,

This is probably a really silly question, but I'm struggling to understand a part of my Python practice problem. I have code that works, but it is doing something that I'm not sure how to fix. I am trying to work with emulating numeric types to have the following output:

>>>p1 = Point(2,3)

>>>p2 = Point(4,5)

>>>id1 = id(p1)

>>>p1 += p2

>>>p1

Point(x=6, y=8)

>>>id1 == id(p1)

True

>>>p2

Point(x=4, y=5)

...Except, my code returns False for id1 == id(p1)

import math

class Point:

"""Two-Dimensional Point(x, y)"""

def __init__(self, x=0, y=0):

self.x=x

self.y=y

def __iter__(self):

yield self.x

yield self.y

def __add__(self, other):

return Point(self.x+other.x, self.y+other.y)

def __mul__(self, n):

return Point(self.x*n, self.y*n)

def __rmul__(self, n):

return Point(n*self.x, n*self.y)

@classmethod

def from_tuple(cls, self=(0,0)):

return cls(*self)

def loc_from_tuple(self, t=(0,0)):

self.x=t[0]

self.y=t[1]

def __str__(self):

return "Point at ({0}, {1})".format(self.x, self.y)

def __repr__(self):

return "Point (x={0}, y={1})".format(self.x, self.y)

@property

def magnitude(self):

return math.sqrt(self.x**2+self.y**2)

def distance(self, other):

return math.sqrt((self.x-other.x)**2+(self.y-other.y)**2)

def shift(p1, p2):

mx=p1.x+p2.x

my=p1.y+p2.y

return Point(mx, my)

What am I misunderstanding that is causing this to make a new object instead of modifying the existing point? Thank you!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!