Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Question: Rewrite moveRect so that it creates and returns a new Rectangle instea

ID: 3619800 • Letter: Q

Question

Question: Rewrite moveRect so that it creates and
returns a new Rectangle instead of modifying the old one.
--
The reading for this question is below:
---
Copying:
Aliasing can make a program difficult to read because changes made in one place
might have unexpected effects in another place. It is hard to keep track of all the
variables that might refer to a given object.
Copying an object is often an alternative to aliasing. The copy module contains
a function called copy that can duplicate any object:
>>> import copy
>>> p1 = Point()
>>> p1.x = 3
>>> p1.y = 4
>>> p2 = copy.copy(p1)
>>> p1 == p2
False
>>> samePoint(p1, p2)
True Once we import the copy module, we can use the copy method to make a new
Point. p1 and p2 are not the same point, but they contain the same data.
To copy a simple object like a Point, which doesn’t contain any embedded objects,
copy is sufficient. This is called shallow copying. For something like a Rectangle, which contains a reference to a Point, copy
doesn’t do quite the right thing. It copies the reference to the Point object, so
both the old Rectangle and the new one refer to a single Point. This is almost certainly not what we want. In this case, invoking growRect on one
of the Rectangles would not affect the other, but invoking moveRect on either
would affect both! This behavior is confusing and error-prone.
Fortunately, the copy module contains a method named deepcopy that copies not
only the object but also any embedded objects. You will not be surprised to learn
that this operation is called a deep copy.
>>> b2 = copy.deepcopy(b1) Now b1 and b2 are completely separate objects. We can use deepcopy to rewrite growRect so that instead of modifying an existing
Rectangle, it creates a new Rectangle that has the same location as the old one
but new dimensions:
def growRect(box, dwidth, dheight) :
   import copy
   newBox = copy.deepcopy(box)
   newBox.width = newBox.width + dwidth
   newBox.height = newBox.height + dheight
   return newBox

Explanation / Answer

class rectangle:
   height = 0;
   width = 0;

def moveRect(box, dwidth, dheight) :
   import copy
   newBox = copy.deepcopy(box);
   newBox.width = newBox.width + dwidth;
   newBox.height = newBox.height + dheight;
   print newBox.width;
   print newBox.height;

box = rectangle();
box.height = 10;
box.width = 20;
moveRect(box,30,30);

raw_input();
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote