Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given

Tags:

python

I have hit a problem with one of the examples in the book Beginning Python Games Development Second Edition.

It has me setting up a vector class (full code at the end of the Q) with the following __init__ function:

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

It then asks me to run this code snippet against it:

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)

The result is the following error:

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

When I put a print on the *A, it comes up as just 2 numbers, as you would expect. Why is it somehow turning this into 4?

Full Vector2 code:

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)
like image 688
Charles Goodwin Jr Avatar asked Aug 04 '15 13:08

Charles Goodwin Jr


1 Answers

A contains three elements, (10.0, 20, 0), because you used a comma, not a . decimal point when defining it:

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

Together with the self argument that means you passed in 4 arguments to the __init__ method.

like image 55
Martijn Pieters Avatar answered Oct 11 '22 03:10

Martijn Pieters