Search code examples
pythonclassself

How to combine same variables in classes


Trying to create a n-body simulation and currently creating a particle class. I initialise the class by inputing a number of variables such as position and velocity. I was wondering if I could somehow combine all the same variable into one array. For instance when I call upon the Particle class it saves all the variables but the variables are all about that particular particle and tied to it. I was wondering if I would be able to find a way to return the velocities for all the particles in one array.

class Particle:

    Position = np.full((1, 3), 0, dtype=float)
    Velocity = np.full((1, 3), 0, dtype=float)
    Acceleration = np.full((1, 3), 0, dtype=float)
    Name = np.full((1, 1), 0, dtype=float)
    Mass = np.full((1, 1), 0, dtype=float)

    """Initialisng all all the data members for each Particle"""

    def __init__(self, Name, Mass, initPosition, initVelocity, initAcceleration):
        self.Name = Name
        self.Mass = Mass
        self.Position = np.array(initPosition)
        self.Velocity = np.array(initVelocity)
        self.Aceleration = np.array(initAcceleration)

    def arrays(self, Positions, Velocities, Accelerations, Names, Masses):
        Positions.append(self.Position)
        Velocities.append(self.Velocity)
        Accelerations.append(self.Acceleration)
        Names.append(self.Name)
        Masses.append(self.Mass)

my second definition "arrays" is trying to to that but unsuccessfully. The aim is so that I can type Positions and a (N,3) matrix is produced upon which I can perform calculations. Is this possible?


Solution

  • I am not sure what you want to do actually:

    If you want to update and return all positions/velocities of one Particle object so you can define:

    def arrays(self, Positions, Velocities, Accelerations, Names, Masses):
        self.Positions = np.append(self.Position, Position)
        self.Velocities = np.append(self.Velocity, Velocity)
        self.Accelerations = np.append(self.Acceleration, Acceleration)
        self.Names = np.append(self.Name, Name)
        self.Masses = np.append(self.Mass, Mass)
    

    and then you can access class properties like:

    p1 = Particle(...)
    p1.Positions
    

    you can update your particle properties from outside and can access it.

    However in your case(i guess at least) you will probably need multiple particle objects. So it is better define a new class that takes particles collection[Particle(*args, **kwargs), Particle(*args, **kwargs), ...] as an input and then you can access all the particles properties and do whatever you want.