Practice Problems 10 Complete before class on 2021-12-03

  1. For the code below:

     class B(A):
         def __init__(self):
             self.a = 4
            
         def set_a(self, value):
             self.a = value
    

    Match the names B, A, a, set_a to the roles below:

    1. method
    2. attribute
    3. base class
    4. derived class
  2. The following class could be used to represent a point in 2-D space:

     class Point:
         """ Point class for representing and manipulating x,y coordinates """
         def __init__(self, x, y):
             """ Create a new point at the given coordinates. """
             self.x = x
             self.y = y
    
         def get_x(self):
             return self.x
    
         def get_y(self):
             return self.y
    
         def distance_from_origin(self):
             return ((self.x ** 2) + (self.y ** 2)) ** 0.5
    

    Assume we executed p = Point(4, 5), which of the following would modify the x attribute?

    1. p.x + 2
    2. p.x += 2
    3. p.x = 3
    4. p.get_x() + 2
    5. p.get_x() += 2
    6. p.get_x() = 3
  3. Using the code above, Point(4, 5) == Point(4, 5) evaluates to False. Why is that? How could you extend the Point class so that above expression returns True when the two points have the same coordinates?

  4. Implement a distance method on Point that returns the distance between the receiver point (the point object on which the method is invoked and another point object).

  5. If you were going to create a new class Point3D for 3-D points (i.e., with x, y and z coordinates) that derived from Point, which of the following methods would you need to override in the Point3D class?

    1. __init__
    2. get_x
    3. get_y
    4. distance_from_origin
  6. Implement the initializer method for the Point3D class described above.

  7. What is printed as this code executes?

     class Foo():
         def __init__(self, a):
             self.a = a
             self.b = 2
    
     class Bar(Foo):
         def __init__(self, c):
             super().__init__(4)
             self.c = c
    
     bar = Bar(6)
     print(bar.a, bar.b, bar.c)