在Python中为类实例添加数组

90 阅读2分钟

在编写一个计算物理项目的代码时,需要为类实例添加一个数组,以便在该类实例的属性中存储数据。 * 在尝试访问类实例的数组时,却发现该数组被返回为空列表。

huake_00152_.jpg

  • 代码示例:
class Particle():
    def __init__(self, (x,y,z), n, radius, neighbours):
        self.n = n
        http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
        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)

# 期望行为:
print(my_particles[0].neighbours)
# 预期输出:[]

# 实际行为:
print(my_particles[0].neighbours)
# 实际输出:[]

2、解决方案

  • 问题根源:

    • 在类 Particle 的初始化方法 __init__ 中,将 neighbours 参数替换为了一个空列表,导致该类实例的 neighbours 属性始终为空。
  • 修复方法:

    • 移除 __init__ 方法中的 neighbours = [] 语句,以允许 neighbours 参数正常传递。
  • 修复后的代码示例:

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
        self.neighbours = neighbours  # <- REMOVE THIS LINE

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)

# 期望行为:
print(my_particles[0].neighbours)
# 预期输出:[]

# 实际行为:
print(my_particles[0].neighbours)
# 实际输出:[]
  • 现在,可以访问类实例的 neighbours 属性,并获得正确的值。