Saint Louis University |
Computer Science 1300
|
Computer Science Department |
Topic: Class Definitions
Related Reading: Chapter 6
Due:
11:00am, Wednesday, 1 November 2017
Please make sure you adhere to the policies on academic integrity.
Exercise 6.2 of the text.
NOTE: For full credit, you must explain the reason for each
error and how it could be corrected.
Also, please note that although the book says there are
five critical errors, it turns out that one of those
errors used to be an error in earlier versions of Python, but
is no longer an error (although it is still not typical
style). So you only need to identify four errors (and
if you wish, can guess what used to be the other error).
(electronic version of that code,
in case you want to see the interpreter's error messages)
For the next two questions, we consider the following
motiviation. In class and in the text, we describe a robust verison of
a Point class that is used to represent
A better approach is to design a single Point class that can be used to model a point with arbitrary dimension. We've started such a class (code here). Internally, we keep a list of coordinates. For uniformity, rather than identifying coordinates with letters like x and y, we use indexing so that the coordinates of a point p can be referenced using a syntax such as p[k] for the kth coordinate (when zero-indexed). We do that by implementing special methods __getitem__ and __setitem__ in lieu of the methods getX, setX getY, and setY from our original Point class definition.
In fact, we can generalize all of the behaviors originally shown in the two-dimensional case. For our new multi-dimensional Point class, we have intentionally omitted implementations for two methods: scale and sum. Your goal is to implement those.
Give a legitimate implementation for the scale method, so that a syntax such as p.scale(3) mutates the state of Point p so that all coordinates are multiplied by the given factor.
Give a legitimate implementation for the __add__ method, so that a syntax such as p + q returns a new Point instance representing the coordinate-wise sum of the original two. You may assume that the syntax will only be invoked upon Points with equal dimension.
Exercise 6.8 of the text.