【问题标题】:Python inheritance for lists of instances实例列表的 Python 继承
【发布时间】:2021-07-20 21:28:41
【问题描述】:

我有一个 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 类并手动添加其属性、函数等的自动方法来获取这样的数组/列表类?

【问题讨论】:

  • 除了定义一个atoms 函数,它需要一个分子列表,我认为没有更简洁的方法可以做到这一点。我会继续使用列表推导。
  • 您是在寻找一种隐藏列表理解的方法,这样您就不必每次都键入它(使用函数),还是想要一种完全避免列表理解的方法?有没有办法可以将分子表示为 np 数组?
  • 分子被定义为具有典型 numpy 数组属性的对象。我已经有几十个函数可以在它们上面运行。我刚开始使用太多的分子,我不能再将它们一一定义为 mol1、...、mol150,我需要使用 molList。我想根据属性(例如最大能量等)或随机选择它们。

标签: python arrays list class inheritance


【解决方案1】:

您可以使用class_variable。可以在这里找到类变量和实例变量之间的区别: https://medium.com/python-features/class-vs-instance-variables-8d452e9abcbd#:~:text=Class%20variables%20are%20shared%20across,surprising%20behaviour%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

【讨论】:

  • 注意:这会为 all 中的原子提供 all 曾经创建的分子。
  • 目的是获取任何属性的列表或数组或访问对象实例的任何函数,而无需为给定属性手动编码某些函数等。
猜你喜欢
  • 1970-01-01
  • 2010-11-08
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 2019-04-03
  • 1970-01-01
相关资源
最近更新 更多