0

I have the following code:

N=200



class Nbody:

num_of_bodies = 0

def __init__(self, x, y, z, vx, vy, vz):
    self.x = x
    self.y = y
    self.z = z
    self.vx = vx
    self.vy = vy
    self.vz = vz

    Nbody.num_of_bodies +=1

def position(self):
    return '{}{}{} {}{} {}{}'.format('(',self.x,',', self.y,',', self.z,')')

nbody_1 = Nbody(random.random(), random.random(), random.random(), 0, 0, 0)
nbody_2 = Nbody(random.random(), random.random(), random.random(), 0, 0, 0)

print(nbody_1.position())
print(nbody_2.position())


print(Nbody.num_of_bodies)

I want to use a loop to create N number of n bodies instead of having to create them manually i.e where nbody_1 and nbody_2 are.

So for instance a loop that for N=200 creates 200 nbody_(i), where i is an integer step between and including 1 and 200.

1
  • For starters, you don't want 200 separate variables; use a list or a dict to store the objects instead. Commented Oct 11, 2018 at 15:22

1 Answer 1

1

You can use a list comprehension:

nbodies = [Nbody(random.random(), random.random(), random.random(), 0, 0, 0)
           for i in range(N)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.