点和线的多类?
我有一个练习。给了我两个类,分别是 Line
(线)和 Point
(点)。我的任务是找出这条线的斜率,并判断一个点是否在这条线上。但是我遇到的问题是,这两个类需要的属性有 x,y,a,b,c
,而 def isonline
这个函数需要用到所有这些属性。所以我做了这些事情。你有什么建议可以帮我解决这个问题吗?
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
class Line:
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def slope(self):
try:
return -self.a/self.b
except ZeroDivisionError:
return None
def isonline(self,Point):
if (self.a*self.x+self.b*self.y+self.c)==0:
return True
else:
return False
coordinatesPoint=Point(4,1)
abcfromLine=Line(10,2,1)
print abcfromLine.slope()
print abcfromLine.isonline(coordinatesPoint)
1 个回答
1
我觉得用 Point.x
和 Point.y
可以解决你的问题。
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
class Line:
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def slope(self):
try:
return -self.a/self.b
except ZeroDivisionError:
return None
def isonline(self, point):
if (self.a*point.x+self.b*point.y+self.c)==0:
return True
else:
return False
coordinatesPoint=Point(4,1)
abcfromLine=Line(10,2,1)
print abcfromLine.slope()
print abcfromLine.isonline(coordinatesPoint)
顺便说一下,我更喜欢用小写字母作为参数。