Python中文
首页
教程
问答
标签
搜索
登录
注册
TypeError:\uu init\uuu()接受1到3个位置参数,但给出了4个
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我对书中的一个例子有意见。</p> <p>它让我用下面的<code>__init__</code>函数设置一个向量类(Q结尾的完整代码):</p> <pre><code>def __init__(self, x=0, y=0): self.x = x self.y = y </code></pre> <p>然后它要求我对它运行此代码片段:</p> <pre><code>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) </code></pre> <p>结果是出现以下错误:</p> <pre><code>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 </code></pre> <p>当我在*a上打印时,如你所料,它只显示2个数字。为什么要把它变成4?</p> <p>完整矢量2代码:</p> <pre><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) </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<pre><code>A = (10.0, 20,0) </code></pre> <p>你应该用</p> <pre><code>A = (10.0, 20.0) </code></pre> <p>所以当你做瞬间</p> <pre><code>Vector(*A) </code></pre> <p>你不会传递4个参数(self,10.0,20,0),但是传递3个参数(self,10.0,20.0)</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
python语法错误(如果不在Z中,则在X中表示s)
3 回答
Python语法错误(无效)概率
10 回答
python语法错误*带有可选参数的args
9 回答
python语法错误2.5版有什么办法解决吗?
1 回答
Python语法错误2.7.4
6 回答
python语法错误30/09/2013
7 回答
Python语法错误E001
10 回答
Python语法错误not()op
7 回答
python语法错误outpu
4 回答
Python语法错误print len()
6 回答
python语法错误w3
9 回答
Python语法错误不是caugh
3 回答
python语法错误及yt-packag的使用
4 回答
python语法错误可以查出来!!瓦里亚布
5 回答
Python语法错误可能是缩进?
1 回答
Python语法错误和缩进
7 回答
Python语法错误在while循环中生成随机numb
10 回答
Python语法错误在哪里?
5 回答
python语法错误在尝试导入包时,但仅在远程运行时
4 回答
Python语法错误在电子邮件地址提取脚本中
10 回答