Numpy: 类实例数组

6 投票
1 回答
18600 浏览
提问于 2025-04-17 19:21

这可能是个傻问题,但假设我想从头开始构建一个程序,像这样:

class Atom(object):
    def __init__(self):
        '''
        Constructor
        '''
    def atom(self, foo, bar):
        #...with foo and bar being arrays of atom Params of lengths m & n
        "Do what atoms do"
        return atom_out

...我可以把我的实例放在一个字典里:

class Molecule(Atom):
    def __init__(self):


    def structure(self, a, b):
        #a = 2D array of size (num_of_atoms, m); 'foo' Params for each atom
        #b = 2D array of size (num_of_atoms, n); 'bar' Params for each atom

        unit = self.atom()
        fake_array = {"atom1": unit(a[0], b[0]),
                      "atom2": unit(a[1], b[1]),
                       :                      :                    :
                       :                      :                    :}

    def chemicalBonds(self, this, that, theother):
        :                         :                      :
        :                         :                      :

我的问题是,有没有办法用numpy数组来实现,让“real_array”中的每个元素都是atom的一个实例——也就是说,是atom函数的单独计算结果?我可以把这个扩展到class Water(molecule):,这样可以对大的structurechemicalBonds输出进行快速的numpy操作,因此需要用到数组……还是说我这样做的方向不对?

另外,如果我在正确的方向上,我会很感激你能给我一些关于如何构建这样的“层次程序”的建议,因为我不太确定我上面做得是否正确,最近发现自己其实并不知道自己在做什么。

提前谢谢你。

1 个回答

8

通往地狱的道路是由过早的优化铺成的……作为一个Python初学者,首先要关注你的程序以及它应该完成的任务。当程序运行得太慢时,再去问如何让它更快。我建议你先学习Python自带的数据结构来管理你的对象。如果你在处理大数组操作,可以使用numpy数组和标准数据类型来实现你的算法。一旦你有了一些能正常工作的代码,就可以进行性能测试,找出需要优化的地方。

Numpy确实允许你创建对象数组,我会给你足够的空间让你自己探索,但要为这些对象数组创建一个工具生态系统并不是一件简单的事情。你应该先学习Python的数据结构(可以参考Beazley的《Essential Python Reference》),然后学习numpy的内置类型,最后再创建你自己的复合numpy类型。如果实在没有办法,才考虑使用下面例子中的对象类型。

祝你好运!

David

import numpy

class Atom(object):
    def atoms_method(self, foo, bar):
        #...with foo and bar being arrays of Paramsof length m & n
        atom_out = foo + bar
        return atom_out


array = numpy.ndarray((10,),dtype=numpy.object)

for i in xrange(10):
    array[i] = Atom()

for i in xrange(10):
    print array[i].atoms_method(i, 5)

撰写回答