gpt4 book ai didi

python - 类型错误 : __init__() takes from 1 to 3 positional arguments but 4 were given

转载 作者:太空狗 更新时间:2023-10-30 02:59:21 26 4
gpt4 key购买 nike

我在 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)

最佳答案

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

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

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

关于python - 类型错误 : __init__() takes from 1 to 3 positional arguments but 4 were given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31811348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com