示例列表的python继承

rdlzhqv9  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(249)

我有一个python对象,具有许多属性和函数(下面是一个虚拟示例):

class molecule:
     def __init__(self, atoms, coords):
         self.atoms=np.copy(atoms)
         self.coords=np.copy(coords)

     def shift(self,r):
         self.coords=self.coords+r

我想生成一个 numpy 数组(或 list )并获取其属性,而不总是在数组上循环。现在我创建了一个分子对象列表( mols )通过循环检查其属性,例如:

atomList=[mol.atoms for mol in mols]

但我更愿意得到:

atomList=mols.atoms

有没有一种不需要手动定义 molList 类并手动添加其属性、函数等?

ivqmmu1c

ivqmmu1c1#

你可以使用 class_variable . 类变量和示例变量之间的区别可以在这里找到:https://medium.com/python-features/class-vs-instance-variables-8d452e9bd#:~:text=class%20variables%20are%20shared%20across,出人意料的是%20behavior%20in%20our%20code。
以你为例,这样的事情应该行得通:

class molecule:
    atomList = []  # class variable
    def __init__(self, atoms, coords):
        self.atoms=np.copy(atoms)  # instance variable
        self.coords=np.copy(coords)
        molecule.atomList.append(atoms) # update the class variable with each new instance of the class

    def shift(self,r):
        self.coords=self.coords+r

在你的代码里,你可以 atomlist = molecule.atomList

相关问题