Classes 2 (Nice)

Warning

The material in this ‘Nice’ chapter is optional. The discussion typically deals with content beyond what a novice should know. So, please finish all the ‘Need’ and ‘Good’ portions before you go through this chapter.

1 Cleaning up with Loops

In my previous discussion on classes, I introduced a class called CParticle1D. I also mentioned how inefficient some of the code was. Now that we know loops, I can quickly clean up my code. Here is a comparison.

class CParticle1D:
    mass = None
    position = None
    radius = None


# Make all the particles identical
CParticle1D.mass = 99
CParticle1D.radius = .01

# Create a list of particles
all_particles = [CParticle1D()]
all_particles += [CParticle1D()]
all_particles += [CParticle1D()]

# Initialise with a random position
i = 0
all_particles[i].position = np.random.rand()

i += 1
all_particles[i].position = np.random.rand()

i += 1
all_particles[i].position = np.random.rand()


i = 0
print(f'Particle {i}: mass={all_particles[i].mass}, position= {all_particles[i].position:.3f}.')
## Particle 0: mass=99, position= 0.715.
i += 1
print(f'Particle {i}: mass={all_particles[i].mass}, position= {all_particles[i].position:.3f}.')
## Particle 1: mass=99, position= 0.885.
i += 1
print(f'Particle {i}: mass={all_particles[i].mass}, position= {all_particles[i].position:.3f}.')
## Particle 2: mass=99, position= 0.469.
class CParticle1D:
    mass = None
    position = None
    radius = None


# Make all the particles identical
CParticle1D.mass = 99
CParticle1D.radius = .01

# Create a list of particles
no_of_particles = 3
all_particles = [CParticle1D() for _ in range(no_of_particles)]

# Initialise with a random position
for particle in all_particles:
    particle.position = np.random.rand()

# Print stuff to check
for count, particle in enumerate(all_particles):
    print(f'Particle {count}: mass={particle.mass}, position= {particle.position:.3f}.')
Particle 0: mass=99, position= 0.715.
Particle 1: mass=99, position= 0.885.
Particle 2: mass=99, position= 0.469.
Back to top