gpt4 book ai didi

python - 为什么我会收到一个显示 "takes no arguments (1 given)"的 TypeError?

转载 作者:IT老高 更新时间:2023-10-28 20:21:29 25 4
gpt4 key购买 nike

我有这段代码来实现粒子群优化算法:

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() 不带参数(给定 1 个)

但它清楚地写着 particle.updateVelocity()() 之间没有任何内容。 “1给定”论点来自哪里?代码有什么问题,如何解决?

最佳答案

Python 隐式地将对象传递给方法调用,但您 need to显式声明它的参数。这通常被命名为 self:

def updateVelocity(self):

关于python - 为什么我会收到一个显示 "takes no arguments (1 given)"的 TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4445405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com