2013-07-08 71 views
61

我是python的新手,並且碰到了一堵牆。我跟着幾個教程,但不能讓過去的錯誤:TypeError:缺少1所需的位置參數:'self'

Traceback (most recent call last): 
    File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module> 
    p = Pump.getPumps() 
TypeError: getPumps() missing 1 required positional argument: 'self' 

我檢查幾個教程,但似乎沒有要任何東西從我的代碼不同。我能想到的唯一的事情是python 3.3需要不同的語法。

主要素文字:

# test script 

from lib.pump import Pump 

print ("THIS IS A TEST OF PYTHON") # this prints 

p = Pump.getPumps() 

print (p) 

水泵類:

import pymysql 

class Pump: 

    def __init__(self): 
     print ("init") # never prints 


    def getPumps(self): 
       # Open database connection 
       # some stuff here that never gets executed because of error 

如果我理解正確的 「自我」 被傳遞給構造函數和方法自動。我在這裏做錯了什麼?

我使用Windows 8與Python 3.3.2

回答

90

這裏需要實例化一個類的實例。

使用

p = Pump() 
p.getPumps() 

小例子 -

>>> class TestClass: 
     def __init__(self): 
      print "in init" 
     def testFunc(self): 
      print "in Test Func" 


>>> testInstance = TestClass() 
in init 
>>> testInstance.testFunc() 
in Test Func 
+6

ABC不是一個很好的示例名稱,因爲它代表了抽象基類。 –

+0

試過之前但卻錯過了「()」。在python 3.x中是新的嗎? – DominicM

+1

糟糕。沒意識到。修復它。抱歉。 –

24

您需要首先初始化:

p = Pump().getPumps() 
+3

簡單性往往被低估。 – theeastcoastwest

+4

這樣做會使p等於方法getPumps(),而這將運行p不會作爲Pump()類的變量「可用」。這不是一個很好的做法,因爲它正在創造一個無用的變量。如果唯一的目標是運行getPumps函數,那麼它只會運行Pump()。getPumps()而不是爲該函數創建一個變量。 – Ashmoreinc

1

您還可以通過提前採取PyCharm的意見標註一個得到這個錯誤方法@staticmethod。刪除註釋。

相關問題