首页 > 解决方案 > 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) 

标签: pythonclassoop

解决方案


您需要初始化 ( self.x1, self.y1) 和 ( self.x2, ) ,self.y2类似于您在. 例如:self.coor1self.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) 

推荐阅读