Skip to main content
 首页 » 编程设计

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

2025年05月04日9yyy_WW

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