Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Dental Assisting

Authors: Doni Bird, Debbie Robinson

13th Edition

978-0323624855, 0323624855

Students also viewed these Programming questions

Question

5. Prepare a brand plan for KitKat.

Answered: 1 week ago