Circle类将Point对象作为圆心。 为了验证圆形实例的中心是一个Point对象,我在 init 中添加了一个if not isinstance()语句。当center不是Point对象时,此if语句引发TypeError。
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!")
但是,代码似乎接受(x,y)形式的任何元组为Point对象。有没有办法只将Point对象传递给中心,其他任何元组都是TypeError?
所需的输出如下所示:
>>> 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!
以下是Point类的代码:
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)
以下是班级圈
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
答案 0 :(得分:1)
这里代码中发生了什么。 当你创建一个带有center = Point(一个Point对象)的圆时,你的代码会创建一个Point,因为你写了
,在Point中作为参数Point.__init__(self,center) # center is a Point object which is not what you want
这不符合中心的默认值(这是一个元组),当你实例化没有中心的Circle对象时,由于元组中心不会传递,这将无效
isinstance(center,Point)
要使用继承,请执行以下操作(同样,不要验证中心是否更有意义):
class Circle(Point):
def __init__(self, center=(0,0), radius=1):
x, y = center
super(Circle, self).__init__(x, y)
self.center = center # This is not useful
self.radius = radius
if not isinstance(center, tuple):
raise TypeError("The center must be a tuple!")
@property
def center(self): # This if a better way to access the center
return(self.x, self.y)