The Circle class takes Point object as the center of circle. To verify the center of the circle instance is a Point object, I added an if not isinstance() statement in init. This if statement raises TypeError when center is not a Point object.
def __init__(self, center=(0,0), radius=1):
Point.__init__(self,center)
self.center=center
self.radius=radius
if not isinstance(center,Point):
raise TypeError("The center must be a Point!")
However, the code seems to accept any tuple in the form of (x,y) to be Point object. Is there a way to only pass the Point object to be center and anything else any tuple to be TypeError?
The desired output is shown in the following:
>>> circle = Circle(center=4, radius=1.5)
[Traceback...]
TypeError: The center must be a Point!
>>> circle = Circle(center=Point(3,4), radius=2)
>>> circle.center = (3, 4)
[Traceback...]
TypeError: The center must be a Point!
The following is the code for Point class:
import math
class Point:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
self.data=[x,y]
def __getitem__(self, index):
return self.data[index]
def __iter__(self):
yield self.x
yield self.y
def __add__(self,other):
return Point(self.x+other.x,self.y+other.y)
def __mul__(self,n):
return Point(self.x*n,self.y*n)
def __rmul__(self,n):
return Point(n*self.x,n*self.y)
@classmethod
def from_tuple (cls, self=(0,0)):
return cls(*self)
def loc_from_tuple(self,t=(0,0)):
self.x=t[0]
self.y=t[1]
def __str__(self):
return "Point at ({0}, {1})".format(self.x,self.y)
def __repr__(self):
return"Point(x={0}, y={1})".format(self.x,self.y)
The following is class Circle
class Circle(Point):
def __init__(self, center=(0,0), radius=1):
Point.__init__(self,center)
self.center=center
self.radius=radius
if not isinstance(center,Point):
raise TypeError("The center must be a Point!")
def __getitem__(self,item):
return self.center[item]
def __str__(self):
return "Circle with center at ({0}, {1}) and radius {2}".format(self.center.x, self.center.y, self.radius)
def __repr__(self):
return "Circle(center=Point({0}, {1}), radius={2})".format(self.center[0],self.center[1],self.radius)
def __add__(self,other):
return Circle(
Point(self.center.x+other.center.x,
self.center.y+other.center.y),
self.radius+other.radius)
@classmethod
def from_tuple(cls, center,radius):
return cls(center, radius)
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
if radius<0:
raise ValueError('The radius cannot be negative')
self._radius=radius