调用Python函数时出错

时间:2015-06-03 19:58:38

标签: python

我定义了一个带有2个参数的函数。当我调用该函数时,我得到一个错误,说没有足够的参数:

bengali

我通过了2和3个参数。第三个论点应该是什么?

2 个答案:

答案 0 :(得分:1)

我假设你在python中不太了解self。它走向OOP(面向对象编程)。

非OOP方法(使用静态方法做同样的事情)

def fib(a,b):
    print a+b

fib(4,8)

OOP方法

class Test():
    i = 0
    j = 0
    def fib(self, a,b):
        self.i=a
        self.j=b
        print self.i+self.j

t = Test() # create an object of Test class
t.fib(2, 3) # make the function call

注意: python认为函数是静态函数,如果它没有关键字self作为第一个参数

答案 1 :(得分:1)

你的函数有3个参数:self,a和b。

self传统上用于方法。

您写的(简化示例):

class A:
   def multiply(self, b): # method called with one argument
       return 2 * b

a = A()
a.multiply(3)

def multiply(b): # this is a function with one argument
    return 2*b

mutiply(3)
相关问题