B
, A
, a
, set_a
to the roles below:
set_a
a
A
B
p = Point(4, 5)
, which of the following would modify the x
instance variable?
p.x + 2
does not modify p.x
because there is no assignment (it just uses p.x
in the computation)p.x += 2
would modify p.x
p.x = 3
would modify p.x
p.get_x() + 2
would not modify p.x
, as with above it just uses the value in the computationp.get_x() += 2
would generate an error, Python does not allow function calls on the left hand side of assignment statementsp.get_x() = 3
would generate an error, Python does not allow function calls on the left hand side of assignment statementsWithout 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
We could implement a distance
method as:
def distance(self, other):
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.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.
A possible init method
def __init__(self, x, y, z):
# Invoke the base class initializer
super().__init__(x, y)
self.z = z
4 2 6