我正在尝试编写一个类圈,这是我第一次使用OOP,为此我也写了一个Point类,但是当我运行contains和intersect函数时,我得到了这个错误信息:
AttributeError: 'Point' object has no attribute 'center'
这是代码:
import math
class Point():
""" Holds data on a point (x,y) in the plane """
def __init__(self, x=0, y=0):
assert isinstance(x,(int, float)) and isinstance(y,(int, float))
self.x = x
self.y = y
def __repr__(self):
return "Point(" + str(self.x) + "," + str(self.y) + ")"
#getters
def x_val(self):
return self.x
def y_val(self):
return self.y
#end of class Point
class Circle():
""" Holds data on a circle in the plane """
def __init__(self,*args):
if len(args)==2:
if isinstance(args[0],Point) and isinstance(args[1],(float,int)):
assert args[1]>0
self.center= args[0]
self.radius= args[1]
if len(args)==3:
assert args[2]>0
self.a=args[0]
self.b=args[1]
self.center= Point(self.a,self.b)
self.radius= args[2]
def __repr__(self):
return "Circle centered at " + str(self.center) + " with radius " + str(self.radius)
def contains(self,check): #ERROR!!!
if isinstance(check,(Point)):
if math.sqrt(((Point.x_val(self.center))-(Point.x_val(check.center)))**2 + ((Point.y_val(check.center))-(Point.y_val(check.center)))**2) <= self.radius:
return True
if isinstance(check,Circle):
test= math.sqrt(((Point.x_val(self.center))-(Point.x_val(check.center)))**2 + ((Point.y_val(self.center))-(Point.y_val(check.center))**2))
if test < (abs((self.radius)-(check.radius))):
return True
else:
return False
def intersect(self,other): #ERROR!!!
check= math.sqrt(((Point.x_val(self))-(Point.x_val(other)))**2 + ((Point.y_val(self))-(Point.y_val(other)))**2)
if check >(self.radius+other.radius):
return False
if check < (self.radius+other.radius):
return True
def draw(self,mat):
for i in mat:
for j in i:
if Circle.contains(i,j):
mat[i[j]]==1
答案 0 :(得分:1)
类Point
的实例没有属性center
,您可以在这三行代码中执行此操作:
if isinstance(check,(Point)):
if math.sqrt(((Point.x_val(self.center))-(Point.x_val(check.center)))**2 + ((Point.y_val(check.center))-(Point.y_val(check.center)))**2) <= self.radius:
return True
如果check
是Point
的实例,请不要参考check.center
。
您可能想要的只是访问Circle的中心的x值和检查点的x。
if isinstance(check,(Point)):
if math.sqrt((self.center.x-check.x)**2 + (self.center.y-check.y)**2) <= self.radius:
return True
请注意,使用方法访问属性被认为不是Python中的好样式。如果要访问属性的值,只需直接访问该属性即可。在某些语言中,如果以后需要更改对象的实现方式,这可能会出现问题,但在Python中,您可以随时将属性更改为属性,而不会破坏代码。