gpt4 book ai didi

Python 使用错误数量的参数调用类方法

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:33 25 4
gpt4 key购买 nike

我刚开始学习 python。我写了一个示例脚本来测试 python 中的 OOP,但发生了一些非常奇怪的事情。当我调用一个类方法时,Python 使用比给定的多一个参数调用该函数。

代码如下:


1. class Bar:
2. num1,num2 = 0,0
3. def __init__(num1,num2):
4. num1,num2 = num1,num2
5. def foo():
6. if num1 > num2:
7. print num1,'is greater than ',num2,'!'
8. elif num1 is num2:
9. print num1,' is equal to ',num2,'!'
10. else:
11. print num1,' is less than ',num2,'!'
12. a,b = 42,84
13. t = Bar(a,b)
14. t.foo
15.
16. t.num1 = t.num1^t.num2
17. t.num2 = t.num2^t.num1
18. t.num1 = t.num1^t.num2
19.
20. t.foo

我得到的错误信息是:


<strong>python test.py</strong>
Traceback (most recent call last):
File "test.py", line 13, in
t = Bar(a,b)
TypeError: <strong>init</strong>() takes exactly 2 arguments (3 given)

有人能帮忙吗?
提前致谢

最佳答案

传递给实例方法的第一个参数是实例本身。通常这在定义函数时称为 self:

  def __init__(self, num1, num2):

考虑阅读 the tutorial .

关于Python 使用错误数量的参数调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2633775/

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