以下代码计算两个坐标之间的距离和斜率。元组拆包是直接在函数.dancee((和.slope((中执行的。我想直接在__init__方法中执行元组拆包。你知道怎么做吗?我试着编制索引,但可能我做错了什么。
class Line():
#We define the variables (attributes of the class)
def __init__(self,coor1,coor2):
self.coor1=coor1
self.coor2=coor2
#We define a function that unpack the tuples and calculates the distance between the points
def distance(self):
x1,y1=self.coor1
x2,y2=self.coor2
return ((x2-x1)**2+(y2-y1)**2)**(1/2)
#We define a function that unpack the tuples and calculate the slope
def slope(self):
x1,y1=self.coor1
x2,y2=self.coor2
return (y2-y1)/(x2-x1)
您需要初始化(self.x1
,self.y1
(和(self.x2
,self.y2
(,类似于在__init__
中定义self.coor1
和self.coor2
的方式。例如:
class Line():
def __init__(self,coor1,coor2):
#self.coor1 = coor1
#self.coor2 = coor2
self.x1, self.y1 = coor1
self.x2, self.y2 = coor2
def distance(self):
return ((self.x2-self.x1)**2+(self.y2-self.y1)**2)**(1/2)
def slope(self):
return (self.y2-self.y1)/(self.x2-self.x1)
您可以使用列表拆包将(x, y)
corinates值定义为
class Cord:
def __init__(self, cord1, cord2):
self.x1, self.y1 = cord1
self.x2, self.y2 = cord2
除此之外,您还可以为cornates点创建一个类,并在类Line中使用该类对象进行计算。以下是样本代码
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Line:
def __int__(self, cord1, cord2):
self.cord1 = cord1
self.cord2 = cord2
def distance(self):
return ((self.cord1.x - self.cord2.x)**2 + (self.cord2.y - self.cord2.y)**2)**0.5
def slope(self):
return (self.cord2.y-self.cord1.y)/(self.cord2.x - self.cord1.x)