python - 创建一个查找线段的斜率和长度的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)
解决方案
发生这种情况是因为您在构造函数中覆盖了您的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))
然后您可以通过简单地访问实例属性来访问length
和slope
属性:
>>> s = Segment((1,2),(3,4))
>>> s.length
8.0
>>> s.slope
1
(还值得注意的是,您的length
功能并不完全正确,但我将把修复留给您!)
推荐阅读
- python - 如何在安装包 phat 时修复 microsofot Visual Studio 中的错误?
- scala - 如何使用 Intellij IDE 运行 MLlib 使用示例?
- html - 如何在 Visual Studio 代码中关闭自动格式化版本:1.35.1(系统设置)
- javascript - 如果 MySQL 数据库中不存在数据,则插入数据,
- excel - 带有可切换范围的索引和匹配
- node.js - Angular 6 应用程序调用本地主机上的 API 被 CORS 阻止
- jquery - 是否有可以在 Ajax 中使用的 if 条件?
- r - 在闪亮的信息框中显示摘要统计信息
- post - 如何在 Blogger 中创建 Next 和 Back 按钮来拆分帖子
- javascript - 获取分组数组的值索引