A more efficient way to determine the number of objects of one type

So, I am in the world of plasma modeling. Now, although I know that top-level simulations are written in fortran and have efficient ultra-memory routines and specialized code, I hope to just run some low-level simulations.

My problem is that when simulating a large number of particles in a time-varying environment (well, with step-by-step time) tracking all of this data is a trick. I used multidimensional arrays before - using the column number for the particle and the row number for the attribute, however this seems pretty awkward. However, it is faster.

I recently tried to define my own class, but as a Python newbie, I probably did it very inefficiently. For each particle in three dimensions, I needed to save the position, speed and strength of the particle (with the possibility of adding additional variables after the code becomes more complex). Using what I knew about classes, I defined an object particle(I think) that makes my code much easier to read and follow:

# Define Particle as a class
class particle():
    def __init__(self, index=0, pos=np.array([0, 0, 0]), vel=np.array([0,0,0]), 
                 F=np.array([0, 0, 0])):
        self.index = index      # Particle index (identifier)
        self.pos = pos          # Position 3-vector
        self.vel = vel          # Velocity 3-vector
        self.F = F              # Net force 3-vector (at particle)

, , , . , , . , - , , .

, , : "" ? / . (.. particle[i].pos = [1,2,3] particle[2].vx[1] = 3), , . , Python, , , .

+4
2

__slots__

- :

class Particle():  # Python 3
    __slots__ = ['index', 'pos', 'vel', 'F']
    def __init__(self, index=0, pos=None, vel=None, F=None):
        # Particle index (identifier)
        self.index = index      
        # Position 3-vector
        self.pos = np.array([0, 0, 0]) if pos is None else pos    
        # Velocity 3-vector
        self.vel = np.array([0,0,0]) if vel is None else vel   
        # Net force 3-vector (at particle)
        self.F = np.array([0, 0, 0]) if F is None else F        

:

, , . __slots__ __dict__ __weakref__ .

: , None NumPy __init__() None.

, , __slots__:

p = Particle()

p.new_attr = 45

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-664-a970d86f4ca3> in <module>()
      1 p = Particle()
      2 
----> 3 p.new_attr = 45

AttributeError: 'Particle' object has no attribute 'new_attr'

__slots__:

class A:   # Python 3
    pass

a = A()
a.new_attr = 10

.

+4

, . , 9 ?

-1

Source: https://habr.com/ru/post/1626447/


All Articles