这可能是个愚蠢的问题,但假设我想像这样自下而上地构建一个程序:
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):
,它将对大型 structure
和 chemicalBonds
输出执行快速 numpy 操作,因此需要数组...还是我的做法不对?
此外,如果我走在正确的轨道上,如果你想提出任何关于如何构建像这样的“分层程序”的提示,我将不胜感激,因为我不确定我是否正确地执行了上述操作并且最近发现我不知道自己在做什么。
提前致谢。
最佳答案
通往 hell 的道路是由过早的优化铺成的...作为 Python 的初学者,专注于您的程序以及应该做什么,一旦它执行得太慢,您可以提出有关如何使其执行的重点问题它更快。我会坚持学习 python 的内在数据结构来管理你的对象。如果您正在执行大型数组操作,则可以使用具有标准数据类型的 numpy 数组来实现您的算法。一旦你有了一些工作代码,你就可以进行性能测试以确定你需要优化的地方。
Numpy 确实允许您创建对象数组,我会在下面给您足够的绳索,但创建一个工具生态系统来操作这些对象数组并非易事。您应该首先使用 python 数据结构(购买 Beazley 的基本 python 引用),然后使用 numpy 的内置类型,然后创建您自己的 compound numpy types .作为最后的手段,使用下面示例中的对象类型。
祝你好运!
大卫
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)
关于python - Numpy:类实例数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15454285/