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
<p><code>A</code>包含<em>三个</em>元素,<code>(10.0, 20, 0)</code>,因为在定义它时使用逗号,而不是<code>.</code>小数点:</p> <pre><code>A = (10.0, 20,0) # ^ that's a comma </code></pre> <p>加上<code>self</code>参数,这意味着您向<code>__init__</code>方法传入了4个参数。</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
上传图片使用Django Ckeditor获取服务器错误(500)
9 回答
上传图片到 Google App Engine,来自非网页客户端
5 回答
上传图片到Djang的cloudinary
7 回答
上传图片到Flask
7 回答
上传图片到googleappengine并与用户分享图片
8 回答
上传图片到googlecolab,并使用Keras预测分类
10 回答
上传图片到s3python
6 回答
上传图片到s3后,上传附带的拇指
4 回答
上传图片在Django,希望是一个循序渐进的指南?
3 回答
上传图片并显示在Django 2.0模板上
10 回答
上传图片时创建动态路径
9 回答
上传多个图像会破坏除第一个Flas之外的所有内容
8 回答
上传多个文件上传文件FastAPI
10 回答
上传多个文件到Django
8 回答
上传多张图片
10 回答
上传大数据到谷歌硬盘给400
7 回答
上传大文件nginx+uwsgi
10 回答
上传大文件不工作谷歌驱动Python API
8 回答
上传大文件到S3
4 回答
上传大文件太慢
7 回答