Python 2.7 TypeError:distance()正好接受2个参数(给定1个)
我试图通过向point类传递参数来检查距离。但当我提供用户输入时,程序随后在计算距离点时失败:Python 2.7 TypeError:distance()正好接受2个参数(给定1个),python-2.7,python-3.x,Python 2.7,Python 3.x,我试图通过向point类传递参数来检查距离。但当我提供用户输入时,程序随后在计算距离点时失败: import math class Point: def __init__(self, x, y): self.x = x self.y = y def distance(self, point): return math.sqrt((self.x-point.x)**2+ (self.y-point.y)**2) class Cir
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, point):
return math.sqrt((self.x-point.x)**2+ (self.y-point.y)**2)
class Circle(Point):
@classmethod
def envelops(self, shape):
if shape == "Circle":
r1 = float(input("Enter radius first circle:"))
r2 = float(input("Enter radius of second circle:"))
x1 = float(input("Enter first circle's x coordinate: "))
x2 = float(input("Enter second circle's x coordinate: "))
y1 = float(input("Enter first circle's y coordinate: "))
y2 = float(input("Enter second circle's y coordinate: "))
Point(x1,y1)
dist=(Point.distance(Point(x2,y2)))
if r1 > (r2 + dist):
print "First Circle envelops the second circle"
else:
pass
if __name__ == "__main__":
shape = 'Circle'
Circle.envelops(shape)
我在执行文件时遇到以下错误:
dist=(Point.distance(Point(x2,y2)))
TypeError: distance() takes exactly 2 arguments (1 given)
我需要立即消除此错误。如有任何帮助,将不胜感激。您有
self
作为距离的参数。因此,调用的不是点距离(x1,y2),而是点1.距离(点2)
另外,点(x1,y1)实际上并没有做任何事情。你需要把它分配到某个地方。像point1=点(x1,y1)
改变:
Point(x1,y1)
dist=(Point.distance(Point(x2,y2)))
致:
说明:distance
不是类方法(静态方法),因此应该在类的对象上调用它,而不是在类本身上调用。因此,第一个调用点(x1,y1)
应该分配给一个变量(这里我使用了x
),然后我们将使用刚刚创建的这个点对象来测量与动态创建的另一个点的距离:点(x2,y2)
我们还可以创建并保存另一点:
x = Point(x1,y1)
y = Point(x2,y2)
dist = x.distance(y) # and now call it with both points
x = Point(x1,y1)
y = Point(x2,y2)
dist = x.distance(y) # and now call it with both points