Python 为什么我新创建的test2对象会影响相同的成员变量pBest
我正试图用test2对象实例化一个名为particles的列表。当我在每个新对象实例化后打印每个test2对象的pBest列表的长度时,可以看到每个instantiation都添加到内存中的相同列表中。为什么每个对象在内存中没有自己的成员变量 我曾尝试使用self.particles.append(copy.deepcopy(test2(numVariables))对新实例化的对象进行深度复制,但也出现了同样的问题Python 为什么我新创建的test2对象会影响相同的成员变量pBest,python,Python,我正试图用test2对象实例化一个名为particles的列表。当我在每个新对象实例化后打印每个test2对象的pBest列表的长度时,可以看到每个instantiation都添加到内存中的相同列表中。为什么每个对象在内存中没有自己的成员变量 我曾尝试使用self.particles.append(copy.deepcopy(test2(numVariables))对新实例化的对象进行深度复制,但也出现了同样的问题 从test2导入test2 课堂测试: 粒子=[] gBest=[] 定义初始化
从test2导入test2
课堂测试:
粒子=[]
gBest=[]
定义初始化(self、numparticle、numvariable):
对于范围内的i(0,numParticles):
self.particles.append(test2(numVariables))
对于self.particles中的j:
印刷品(len(j.pBest))
p=试验(5,2)
随机导入
类test2:
速度=[]
职位=[]
pBest=[]
定义初始值(自身,数值变量):
对于范围内的i(0,numVariables):
self.velocies.append(random.random())
self.positions.append(random.random())
self.pBest.append(float('inf'))
我预计产出为:
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
但结果是:
2
4
4
6
6
6
8
8
8
8
10
10
10
10
10
pBest
在您的示例中是静态的(这意味着所有类实例都可以访问相同的变量)。将其移动到构造函数将修复它:
class test2:
def __init__(self, numVariables):
self.velocities = []
self.positions = []
self.pBest = []
for i in range(0, numVariables):
self.velocities.append(random.random())
self.positions.append(random.random())
self.pBest.append(float('inf'))
在类作用域中定义变量使它们成为类成员,而不是实例成员