我必须写一段代码,通过两个对象的传值来寻找两个点之间的不同,如下图所示,但我得到了TypeError。类型错误:init() 缺少了3个必要的位置参数,'x'、'y'和'z'。'x', 'y', 和'z'。
class Point:
def __init__(self, x, y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(point: {},{},{})'.format(self.x, self.y, self.z)
def distance(self, other):
return sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )
p = Point()
p1 = Point(12, 3, 4)
p2 = Point(4, 5, 6)
p3 = Point(-2, -1, 4)
print(p.distance(p1,p3))
你没有传递所需的3个参数给 p = Point()
修正你的错误
from math import sqrt
class Point:
def __init__(self, x, y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(point: {},{},{})'.format(self.x, self.y, self.z)
def distance(self, other):
return sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )
# p = Point() # not required
p1 = Point(12, 3, 4)
p2 = Point(4, 5, 6)
p3 = Point(-2, -1, 4)
print(p1.distance(p3)) # use this to find distance between p1 and any other point
# or use this
print(Point.distance(p1,p3))
class Point:
def __init__(self, x, y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(point: {},{},{})'.format(self.x, self.y, self.z)
def distance(self, other):
return math.sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )
p1 = Point(12, 3, 4)
p2 = Point(4, 5, 6)
p3 = Point(-2, -1, 4)
print(Point.distance(p1,p3))
它的工作原理是这样的.你不应该定义一个 P
点比其他三个点分开。每个点都是一个独立的实例。但是当你尝试使用函数时,只是调用类。
问题就出在这一行。
p = Point()
当你定义你的类时,你指定了它必须被传递3个参数来初始化它(def __init__(self, x, y,z)
).
如果你仍然想在不传递这3个参数的情况下创建这个点对象,你可以像这样把它们变成可选的。
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
这样,如果你不指定这些参数(就像你做的那样),它将默认创建一个坐标为{0, 0, 0}的点。