为什么会出现“没有参数(给了1个)”的类型错误?

68 投票
4 回答
139134 浏览
提问于 2025-04-16 08:33

我有一段代码是用来实现粒子群优化算法的:

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)

当我运行这段代码时,出现了这个错误:

TypeError: updateVelocity() takes no arguments (1 given)

但是它明显写的是particle.updateVelocity(),在()之间什么都没有。那么“1 given”的参数是从哪里来的呢?代码哪里出错了,我该怎么修复它?

4 个回答

6

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

8

确保你所有的类方法(比如 updateVelocityupdatePosition 等)都至少有一个位置参数,这个参数通常叫做 self,它代表当前这个类的实例。

当你调用 particle.updateVelocity() 时,被调用的方法会自动接收到一个参数:就是这个实例,这里是 particle,作为第一个参数传进去。

133

在Python中,当你调用方法时,Python会自动把对象传递给这个方法。不过,你需要明确地声明这个参数。通常,这个参数叫做 self

def updateVelocity(self):

撰写回答