创建一个查找线段斜率和长度的python类

问题描述 投票:0回答:1

我需要弄清楚如何创建一个类来找到线段的斜率和长度,并传递两个表示端点为(x,y)的元组。我的问题是,当我尝试创建细分对象时,它说int对象不可调用。请帮助

class Segment():
    def __init__(self, tup1, tup2):
            self.x1 = tup1[0]
            self.x2 = tup2[0]
            self.y1 = tup1[1]
            self.y2 = tup2[1]
            self.slope = 0
            self.length = 0

    def length(self):
            self.length = math.sqrt((y2-y1)**(2+(x2-x1)**2))
            print(self.length)

    def slope(self):
            self.slope = ((y2-y1)/(x2-x1))
            print(self.slope)
python class
1个回答
0
投票

发生这种情况是因为您正在覆盖构造函数中的length属性。因此,当您尝试调用s.length()时,实际上是在尝试调用0(),因为您分配了self.length = 0

您可能应该做类似的事情(请注意,我在每个x和y值前加self前缀,因此它使用实例的属性值):

class Segment():
    def __init__(self, tup1, tup2):
        self.x1 = tup1[0]
        self.x2 = tup2[0]
        self.y1 = tup1[1]
        self.y2 = tup2[1]

        self.length = math.sqrt((self.y2-self.y1)**(2+(self.x2-self.x1)**2))
        self.slope = ((self.y2-self.y1)/(self.x2-self.x1))

然后您可以通过简单地访问实例属性来访问lengthslope属性:

>>> s = Segment((1,2),(3,4))
>>> s.length
8.0
>>> s.slope
1
© www.soinside.com 2019 - 2024. All rights reserved.