TypeError:\uu init\uuu()接受1到3个位置参数,但给出了4个

2024-04-20 06:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我对书中的一个例子有意见。

它让我用下面的__init__函数设置一个向量类(Q结尾的完整代码):

def __init__(self, x=0, y=0):
    self.x = x
    self.y = y

然后它要求我对它运行此代码片段:

from Vector2 import *

A = (10.0, 20,0)
B = (30.0, 35.0)
AB = Vector2.from_points(A, B)
step = AB * .1
position = Vector2(A, B)
step = AB * .1
print(*A)
position = Vector2(*A)
for n in range(10):
    position += step
    print(position)

结果是出现以下错误:

Traceback (most recent call last):
  File "C:/Users/Charles Jr/Dropbox/Python/5-14 calculating positions.py", line 10, in <module>
    position = Vector2(*A)
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given

当我在*a上打印时,如你所料,它只显示2个数字。为什么要把它变成4?

完整矢量2代码:

import math

class Vector2:

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)

    def from_points(P1, P2):
        print("foo")
        return Vector2( P2[0] - P1[0], P2[1] - P1[1])

    def get_magnitude(self):
        return math.sqrt( self.x**2 + self.y**2 )

    def normalise(self):
        magnitude = self.get_magnitude()
        self.x /= magnitude
        self.y /= magnitude

    # rhs stands for right hand side
    def __add__(self, rhs):
        return Vector2(self.x + rhs.x, self.y + rhs.y)

    def __sub__(self, rhs):
        return Vector2(self.x - rhs.x, self.y - rhs.y)

    def __neg__(self):
        return Vector2(-self.x, -self.y)

    def __mul__(self, scalar):
        return Vector2(self.x * scalar, self.y * scalar)

    def __truediv__(self, scalar):
        return Vector2(self.x / scalar, self.y / scalar)

Tags: 代码fromselfreturnabinitdefstep
2条回答

A包含三个元素,(10.0, 20, 0),因为在定义它时使用逗号,而不是.小数点:

A = (10.0, 20,0)
#            ^ that's a comma

加上self参数,这意味着您向__init__方法传入了4个参数。

A = (10.0, 20,0)

你应该用

A = (10.0, 20.0)

所以当你做瞬间

Vector(*A)

你不会传递4个参数(self,10.0,20,0),但是传递3个参数(self,10.0,20.0)

相关问题 更多 >