Jacob Hermann Olesen Jacob Hermann Olesen - 1 month ago 6
Python Question

create list with variables containing classes

I am trying to create my own Nbody simulation from scratch. I have created a class (called Body) that contains functions to calculate the forces from the other bodies and move it accordingly.
I have created another class, called System, that defines the number of bodies, controls the updates of the positions and updates a plot of the system.
Both classes work fine if I define the number of variables individually like this:

d1 = Body(i)
d2 = Body(i)
....


and put them in a list
list = [d1,d2, ...]
. i is a string (a name that is used
The problem with this method is that it is tiresome to do n individual variable definitions and then put them in a list. I have tried to do a loop:

self.liste = []
for i in range(n):
self.liste.append(Body(str(i)))


but this returns a list containing Nonetypes (
[None, None, None, ....]
).
It is important to my setup that I end up with a list n different classes (it is okay if they are defined by a variable name). Can anybody help me with this?

Answer

The following works for me:

class Body:
    bodies = []
    def __init__(self, n):
        self.n = n

    def __str__(self):
        return str(self.n)

for i in range(5):
    Body.bodies.append(Body(i))

for body in Body.bodies:
    print body
    # This also works.
    print body.n

Note that if you directly try and print a class, you need a __str__ (or __repr__) method.