「引数がありません (1 個指定)」という TypeError が表示されるのはなぜですか? [重複] 質問する

「引数がありません (1 個指定)」という TypeError が表示されるのはなぜですか? [重複] 質問する

粒子群最適化アルゴリズムを実装するためのコードは次のとおりです。

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」引数はどこから来ているのでしょうか? コードのどこが間違っているのでしょうか? また、どのように修正すればよいのでしょうか?

ベストアンサー1

Pythonは暗黙的にオブジェクトをメソッド呼び出しに渡しますが、必要明示的にパラメータを宣言します。これは通常次のように命名されますself:

def updateVelocity(self):

おすすめ記事