How can `__init__` refuse to build a Circle at all when the centre you hand it isn't a Coordinate?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The Circle class below has an empty __init__. Give it a body so that a circle keeps the two things it is handed as the data attributes self.center and self.radius.
Then build one circle: its center sits at x = 3, y = -1, and its radius is the int 5. Assign the circle object to my_circle.
The center has to be a Coordinate object, so work from the inside out — the coordinate must exist before the circle can hold it.
class Coordinate(object):
""" A coordinate made up of an x and y value """
def __init__(self, x, y):
""" Sets the x and y values """
self.x = x
self.y = y
def distance(self, other):
""" Returns the euclidean distance between two Coordinate objects """
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5The design decision behind the Circle data type
Write the plain __init__ setting self.center and self.radius, record that the centre is a Coordinate object and the radius an int, and contrast the radius-only circle of the earlier exercise.
Type checks that raise ValueError
Write the guarded constructor testing type(center) != Coordinate and type(radius) != int ahead of both assignments, and trace Circle(2, 2) and Circle(center, 'two') raising ValueError.
is_inside reusing a method of another class
Write return point.distance(self.center) < self.radius, trace a circle centred at (2, 2) with radius 2 against Coordinate(1, 1) giving True and Coordinate(10, 10) giving False.