Python编译器错误,x不需要参数(1给出)

问题描述:

我正在写一小段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://*.com/q/6614123/448474 – hynekcer 2012-12-13 12:28:46

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

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__)有同样的问题。

确保,即所有的类方法(updateVelocityupdatePosition,...)至少需要一个位置参数,这是规范地命名为self,指的是类的当前实例。

当您调用particle.updateVelocity()时,被调用方法隐式获取参数:实例,此处为particle作为第一个参数。

我一直对这个问题感到困惑,因为我是Python中的新手。我无法将解决方案应用于提问中给出的代码,因为它不是可自行执行的。所以我带来了非常简单的代码:

from turtle import * 

ts = Screen(); tu = Turtle() 

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

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

done() 

正如你可以看到,该解决方案包括在使用两个哑变量,即使他们也不由函数本身或调用它用!这听起来很疯狂,但我相信它一定有一个原因(隐藏于新手!)。

我尝试了很多其他方式(包括“自我”)。这是唯一可行的(至少对我而言)。