【发布时间】:2015-07-29 20:29:59
【问题描述】:
我使用AB = Vector2.from_points(A, B) 行创建了类 Vector2 的实例
但是 TypeError: object() takes no parameters 出现 python 错误
在线AB = Vector2.from_points(A,B)
在线return Vector2(cls, P2[0]-P1[0], P2[1]-P1[1])
所以我认为这本书可能是错误的(我正在查看书中的示例)。我从 def from_points 语句中减去 Vector2 和 cls,这样......
这就是新行的写法:return (P2[0]-P1[0], P2[1]-P1[1])
当我这样做时,从 def from_points 接收向量值也等于 (5, 10)
但随后出现 python 错误:
print AB.get_magnitude()
AttributeError: 'tuple' object has no attribute 'get_magnitude'
所以没有与 Vector2 和 cls 相关的代码,程序不会将 AB 读取为类对象,但似乎我没有正确格式化它,所以它不会通过。
我已经坚持了好几天了。
#Vector Test
import math
class Vector2(object):
def _init_(self, x=0.0,y=0.0):
self.x = x
self.y = y
def _str_(self):
return"(%s,%s)"%(self.x,self.y)
@classmethod
def from_points(cls, P1, P2):
return Vector2(cls, P2[0]-P1[0],P2[1]-P1[1])
def get_magnitude(self):
return math.sqrt(self.x**2 + self.y**2)
A = (15.0, 20.0)
B = (20.0, 30.0)
AB = Vector2.from_points(A, B)
print AB
print AB.get_magnitude()
更改代码:
#Vector Test
import math
class Vector2(object):
def _init_(self, x=0.0,y=0.0):
self.x = x
self.y = y
def _str_(self):
return"(%s,%s)"%(self.x,self.y)
@classmethod
def from_points(cls, P1, P2):
return (P2[0]-P1[0],P2[1]-P1[1])
def get_magnitude(self):
return math.sqrt(self.x**2 + self.y**2)
A = (15.0, 20.0)
B = (20.0, 30.0)
AB = Vector2.from_points(A, B)
print AB
print AB.get_magnitude()
【问题讨论】:
-
Vector2 是 cls。使用一个或另一个,而不是两者都从点构建
-
另外,__init__ 和 __str__ 也需要双下划线
-
请考虑修改您在此问题中发布的代码示例。就目前而言,它的格式和范围使我们很难为您提供帮助;这是一个great resource,可以帮助您开始。 -1,不要走错路。否决票是我们在这里指出内容问题的方式;改进您的格式和代码示例,我很乐意将其还原。祝你的代码好运!就我个人而言,我认为在你的缩进上工作会很好。
-
哇,我在 6 年前没有任何意义。