TypeError:__ init __()取1到3个位置参数,但给出了4个

时间:2015-08-04 13:57:40

标签: python

我遇到了Beginning Python Games Development Second Edition一书中的一个例子的问题。

我让我使用以下__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?

完整Vector2代码:

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)

2 个答案:

答案 0 :(得分:4)

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

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

self参数一起表示您将4个参数传递给__init__方法。

答案 1 :(得分:0)

A = (10.0, 20,0)

你应该使用

A = (10.0, 20.0)

所以当你做instanciate

Vector(*A)

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