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

标签 python oop parameters methods

我刚开始学习 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/

相关文章:

python - Pygame 碰撞一次发生 19 次 - Python 3.x

javascript - 如何修改对象 getter 返回的私有(private)变量?

python - 如何使 argparse 仅适用于一个参数,即使传递了许多参数?

Python-在脚本后台运行 while 循环

python - 我如何使用 scikit learn 迭代 python 中的 'list' 模型?

c# - 如何在设置类型等方法中设置参数

powershell - 为什么 Get-content 支持 -wait 参数?

swift - 继承中的枚举

c++ - 使用三个参数重载 operator new 和 operator delete

java - 如何在 Java 中传递应该具有三个值的单个参数?