2010-12-14 28 views
48

我正在寫一小段python作爲家庭作業,並且我沒有讓它運行!我沒有那麼多的Python體驗,但我知道很多Java。 我試圖實現粒子羣算法,這裏就是我:Python編譯器錯誤,x不需要參數(1給出)

class Particle:  

    def __init__(self,domain,ID): 
     self.ID = ID 
     self.gbest = None 
     self.velocity = [] 
     self.current = [] 
     self.pbest = [] 
     for x in range(len(domain)): 
      self.current.append(random.randint(domain[x][0],domain[x][1])) 
      self.velocity.append(random.randint(domain[x][0],domain[x][1])) 
      self.pbestx = self.current   

    def updateVelocity(): 
    for x in range(0,len(self.velocity)): 
     self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 * random.random()*(self.gbest[x]-self.current[x]) 


    def updatePosition():  
     for x in range(0,len(self.current)): 
      self.current[x] = self.current[x] + self.velocity[x]  

    def updatePbest(): 
     if costf(self.current) < costf(self.best): 
      self.best = self.current   

    def psoOptimize(domain,costf,noOfParticles=20, noOfRuns=30): 
     particles = [] 
     for i in range(noOfParticles):  
      particle = Particle(domain,i)  
      particles.append(particle)  

     for i in range(noOfRuns): 
      Globalgbest = [] 
      cost = 9999999999999999999 
     for i in particles:  
     if costf(i.pbest) < cost: 
       cost = costf(i.pbest) 
      Globalgbest = i.pbest 
      for particle in particles: 
       particle.updateVelocity() 
       particle.updatePosition() 
       particle.updatePbest(costf) 
       particle.gbest = Globalgbest  


     return determineGbest(particles,costf) 

現在,我看不出有任何理由爲什麼這不應該工作。 然而,當我運行它,我得到這個錯誤:

「類型錯誤:updateVelocity()函數沒有(給定1)參數」

我不明白!我沒有給出任何論點!

感謝您的幫助,

萊納斯

+0

請突出顯示您的代碼並點擊「010101」按鈕進行正確格式化。 – 2010-12-14 23:40:36

+0

我的源代碼中沒有空白行,這只是本網站格式化它的方式。 – Linus 2010-12-15 22:26:14

+1

質量差的問題:許多不相關的代碼,由於混合的空格和製表符而導致許多語法錯誤。重複更好的問題http://stackoverflow.com/q/6614123/448474 – hynekcer 2012-12-13 12:28:46

回答

99

Python的隱含傳遞對象的方法調用,但是你需要顯式聲明的參數吧。這是習慣命名爲self

def updateVelocity(self): 
+0

哦,太棒了!謝謝! – Linus 2010-12-14 23:45:18

+4

我剛開始學習python。至少現在我認爲這很醜陋。 – shaffooo 2016-05-07 21:09:07

+0

@fred我很好奇你是通過在IronPython項目上工作時一路探索學到這些知識的嗎,或者你有沒有辦法調試這種類型的錯誤?無論哪種方式,我很想學習= D – 2016-08-09 10:19:26

5

updateVelocity()方法缺少在定義明確self參數。

應該是這樣的:

def updateVelocity(self):  
    for x in range(0,len(self.velocity)): 
     self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 \ 
      * random.random()*(self.gbest[x]-self.current[x]) 

你的其他方法(除了__init__)有同樣的問題。

6

確保,即所有的類方法(updateVelocityupdatePosition,...)至少需要一個位置參數,這是規範地命名爲self,指的是類的當前實例。

當您調用particle.updateVelocity()時,被調用方法隱式獲取參數:實例,此處爲particle作爲第一個參數。

0

我一直對這個問題感到困惑,因爲我是Python中的新手。我無法將解決方案應用於提問中給出的代碼,因爲它不是可自行執行的。所以我帶來了非常簡單的代碼:

from turtle import * 

ts = Screen(); tu = Turtle() 

def move(x,y): 
    print "move()" 
    tu.goto(100,100) 

ts.listen(); 
ts.onclick(move) 

done() 

正如你可以看到,該解決方案包括在使用兩個啞變量,即使他們也不由函數本身或調用它用!這聽起來很瘋狂,但我相信它一定有一個原因(隱藏於新手!)。

我嘗試了很多其他方式(包括「自我」)。這是唯一可行的(至少對我而言)。

相關問題