Practice Problems 10 Solution

  1. Match the names B, A, a, set_a to the roles below:
    1. method: set_a
    2. attribute: a
    3. base class: A
    4. derived class: B
  2. Assume we executed p = Point(4, 5), which of the following would modify the x attribute?
    1. p.x + 2 does not modify p.x because there is no assignment (it just uses p.x in the computation)
    2. p.x += 2 would modify p.x
    3. p.x = 3 would modify p.x
    4. p.get_x() + 2 would not modify p.x, as with above it just uses the value in the computation
    5. p.get_x() += 2 would generate an error, Python does not allow function calls on the left hand side of assignment statements
    6. p.get_x() = 3 would generate an error, Python does not allow function calls on the left hand side of assignment statements
  3. Without overriding the __eq__ method, Python performs object equality by comparing references, that is do the left-hand and right-hand side expressions point to the same object in memory. That is not the case here since we are comparing to newly created object. To achieve the desired behavior we would implement the following method:

      def __eq__(self, other):
         return self.x == other.x and self.y == other.y
    
  4. We could implement a distance method as:

     def distance(self, other):
         return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
    
  5. The Point3D class would inherit the x and y-coordinates, and add a z-coordinate. We would need to override the __init__ and distance_from_origin methods, but not get_x and get_y. Those could be used as is, as we would not change the behavior of the x and y-coordinates.

  6. A possible init method

     def __init__(self, x, y, z):
         # Invoke the base class initializer
         super().__init__(x, y)
         self.z = z
    
  7. The code prints 4 2 6