簡體   English   中英

調用Python函數時出錯

[英]Error while calling Python function

我定義了一個帶有2個參數的函數。 調用該函數時,出現錯誤,提示參數不足:

>>> def fib(self, a,b):
...   self.i=a, self.j=b
...   print self.i+self.j
... 
>>> fib(4,8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fib() takes exactly 3 arguments (2 given)

>>> fib(4,8,9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fib
AttributeError: 'int' object has no attribute 'i'

我通過了2和3參數。 第三個論點應該是什么?

我假設您在python中不太了解self 面向OOP(面向對象編程)的方向。

非OOP方法(使用靜態方法做同樣的事情)

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

fib(4,8)

面向對象的方法

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作為第一個參數,則該函數將其視為靜態函數

您的函數具有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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM