我正在为计算物理项目编写代码。
我想知道如何通过在类的实例中添加一个数组来实现python中的类。
这是我原来的代码部分:
class Particle():
def __init__(self, (x,y,z), n, radius, neighbours):
self.n = n
self.x = x
self.y = y
self.z = z
self.radius = radius
number = loadtxt("final_limited.txt", usecols=(0,), unpack=True, dtype = int)
c1,c2,c3,r = loadtxt("final_limited.txt", usecols=(1,2,3,5), unpack=True, dtype=float)
number_of_particles = len(number)
my_particles = []
overlap = []
contact_number = []
for i in range(number_of_particles):
n = number[i]
x = c1[i]
y = c2[i]
z = c3[i]
radius = r[i]
neighbours = []
particle = Particle((x,y,z), n, radius, neighbours)
my_particles.append(particle)
for particle1 in my_particles:
count = 0
for particle2 in my_particles:
distance = PBCdist(particle1, particle2)
sum_of_radii = Sum_radii(particle1, particle2)
if (distance < sum_of_radii) and (distance>0):
count +=1
olap = (Decimal(sum_of_radii) - Decimal(distance))
overlap.append(olap)
contact_number.append(count)
我想做以下事情:
class Particle():
def __init__(self, (x,y,z), n, radius, neighbours):
neighbours = []
self.n = n
self.x = x
self.y = y
self.z = z
self.radius = radius
self.neighbours = neighbours
然后,在嵌套循环中:
for particle1 in my_particles:
count = 0
for particle2 in my_particles:
distance = PBCdist(particle1, particle2)
sum_of_radii = Sum_radii(particle1, particle2)
if (distance < sum_of_radii) and (distance>0):
count +=1
neighbours.append(particle2.n)
olap = (Decimal(sum_of_radii) - Decimal(distance))
overlap.append(olap)
contact_number.append(count)
正如您所看到的,我想将每个粒子的关联作为其邻居列表作为该类的每个元素的属性。
但是,当我检查它时,此代码不起作用。我希望能说出类型:
print my_particles[0].neighbours
获取清单。
此外,你知道是否有一个像浮动的Numpy dtype可以给我所需的20-21位小数?使用float数据类型我的代码当然更快(10次),但我想使用一个允许完全精度的numpy类型,而不是Decimal。
答案 0 :(得分:2)
使用空列表替换neighbors参数
def __init__(self, (x,y,z), n, radius, neighbours):
neighbours = [] # <- HERE
self.neighbours = neighbours
删除该行,您应该能够访问邻居列表。