0

我正在为计算物理项目编写代码。

我想知道如何通过向类的实例添加一个数组来在 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)

正如你所看到的,我想给每个粒子关联它的邻居列表作为类的每个元素的属性。

但是,当我检查它时,此代码不起作用。我希望 tp 能够说类型:

print my_particles[0].neighbours

并获取列表。

此外,您知道是否有像 float 这样的 Numpy dtype 可以给我所需的 20-21 位小数?使用浮点数据类型我的代码当然更快(10 倍),但我想使用允许需要全精度的 numpy 类型,而不是十进制。

4

1 回答 1

2

您用空列表替换邻居参数

def __init__(self, (x,y,z), n, radius, neighbours):
     neighbours = []  # <- HERE
     self.neighbours = neighbours

删除该行,您应该能够访问邻居列表。

于 2013-07-03T13:37:51.633 回答