首页 > 解决方案 > 创建一个查找线段的斜率和长度的python类

问题描述

我需要弄清楚如何创建一个类,该类找到线段的斜率和长度,并传递两个将端点表示为 (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)

标签: pythonclass

解决方案


发生这种情况是因为您在构造函数中覆盖了您的self.length方法0。因此,当您尝试调用时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

(还值得注意的是,您的length功能并不完全正确,但我将把修复留给您!)


推荐阅读