有人可以看到问题吗?我想我在frompoints函数中传递了三个参数,而不是四个,对吗?
class vector2D:
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __str__(self):
return "({}, {})".format(self.x, self.y)
@classmethod
def frompoints(cls, P1, P2):
x = P2[0] - P1[0]
y = P2[1] - P1[1]
return vector2D(cls, x, y)
P1 = (10.0, 5.0)
P2 = (17.0, 10.0)
v2 = vector2D.frompoints(P1, P2)
错误信息:
Traceback (most recent call last):
File "D:/Pycharm/Testy/test.py", line 22, in <module>
v2 = vector2D.frompoints(P1, P2)
File "D:/Pycharm/Testy/test.py", line 17, in frompoints
return vector2D(cls, x, y)
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given
在这种情况下cls
,a中的参数@classmethod
是类本身vector2D
。您不会在其他地方将类作为参数传递(不是vector2D(vector2D, x, y)
),那么为什么在这里呢?
可能使您感到困惑的是,您可以在类上调用实例方法,并显式传递实例作为第一个参数:
vector2D.__init__(instance, x, y)
然而,frompoints
是一个类的方法,所以你还不具备的情况下通过。您应该这样做:
return cls(x, y)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句