【发布时间】:2022-01-25 06:08:11
【问题描述】:
我需要通过使用 Circle 类来确定 c1 和 c2 两个圆是否在外部且仅在一个点上相互接触。 我创建了接触的方法。该方法应该返回一个布尔值,它需要像这样调用 c1.touches(c2)
这个公式检查圆圈是否相互接触或相交formula
这是我的代码
import math
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
def touches(self):
dist_between_centers = math.sqrt((self.c1.x - self.c2.x)^(2 + (self.c1.y - self.c2.y)^2))
if dist_between_centers == (self.c1.r + self.c2.r):
print("True")
elif dist_between_centers > (self.c1.r + self.c2.r):
print("False")
else:
print("False")
c1 = Circle(2,3,12)
c2 = Circle(15, 28, 10)
c1.touches(c2)
但是我遇到了这样的错误,TypeError: touches() 需要 1 个位置参数,但给出了 2 个
【问题讨论】:
-
touches不带参数(self类除外),但你用一个来调用它:c1.touches(c2) -
当我调用它 c1.touches(c2) 我收到类型错误 c1.touches(c2) TypeError: touches() 需要 1 个位置参数,但给出了 2 个
-
您粘贴的代码有问题。如果您将
touches称为c1.touches(c2),那么您在touches中访问self.c1和self.c2是很奇怪的。请仔细查看并修复它。 -
您应该阅读
self在类函数中的含义,以及为什么您的c2参数实际上是第二个参数。 -
请注意,由于我们不检查交叉点,因此不需要第二次检查,它会触及或不触及。它可能应该返回 boolean
TrueandFalse而不是字符串"True"和"False"。