python - Python - 如何在类中执行元组解包
问题描述
以下代码计算两个坐标之间的距离和斜率。元组解包直接在函数 .distance() 和 .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
类似于您在. 例如:self.coor1
self.coor2
__init__
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)
推荐阅读
- java - 是否有任何解决方案可以在达到 maxmemory 时从后端和前端从 redis 流 1 中删除消息
- python-3.x - 利用 ExternalTaskSensor 的 DAG 持续运行
- python - 使用 SQL/TKinter (Python) 将变量传递给第二个脚本
- r - 使用 optim 将条件应用于优化的参数
- python - 快速合并 Pandas 中的行
- c++ - 包括“Y”在内的元音数
- python - 使用带有矩阵数据集的 PyPI 包传输熵计算
- javascript - 检查复选框是否被选中
- javascript - 每当从 html 按下按钮时,有没有办法让 puppeteer 启动?
- moodle - Moodle:隐藏“您的网站尚未注册”消息