![](https://secure.gravatar.com/avatar/764323a14e554c97ab74177e0bce51d4.jpg?s=120&d=mm&r=g)
On Fri, Nov 21, 2008 at 20:37, Benjamin J. Racine <bjracine@glosten.com> wrote:
Hello all,
Please let me know if I should be posting just general OO stuff somewhere else, but I figure that this might be relevant to a lot of procedural programming types just jumping into python (and the example is straight out of FEA). Anyways, I have the following code below. The problem is, I need to be able to instantiate many nodes for a given element as well as many elements for a model. Tackling this with built-ins such as arrays, lists and dicts seems straightforward, but I can't wrap my head around it in OO for some reason. Do I just need to make my element and node inherit from a list and then use the ".append()" when I instantiate it?
If the builtin types work well, then go ahead and use them. OO doesn't solve every problem, but it can certainly create a few. In languages like C++, where the builtin types are so limited, being able to write classes helps a lot. But in Python, lists, dicts, and arrays are relatively awesome (and are already OO objects) so writing your own classes is sometimes a downgrade. In any case, you will want to make use of lists, dicts, and arrays if you need collections. You almost certainly don't want nested class declarations. Try this on for size: class Model(object): """ An FEA model. """ def __init__(self, elements): self.elements = elements class Element(object): """ A single element of an FEA model. """ def __init__(self, element_id, pressure, nodes): self.element_id = element_id self.pressure = pressure self.nodes = nodes class Node(object): """ A node in an FEA model. """ def __init__(self, node_id, xyz): self.node_id = node_id self.xyz = xyz model = Model(elements=[ Element(1, 0.0, nodes=[ Node(1, (1,2,3)), Node(2, (3,4,5)), Node(3, (6,7,8)), ]), ]) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco