Hi,
I'm fairly new to Python but especially new to Object Oriented programming. Currently, I am writing code to simulate gas molecules in a container. Essentially, one of the things I need my code to do is, create a ball object with a certain position and velocity, and then have it collide with the wall of the container. When it bounces back, it should have a new velocity. I have worked out all of the formulae necessary for this.
Firstly, I create a class Ball, which is initialised with mass = 1 and radius = 1 (these are not very important for my question).
class Ball():
def __init__(self, pos = np.array([0,0]), vel = np.array([0,0]), mass = 1, radius = 1):
self.mass = mass
self.radius = radius
self.pos = pos
self.vel = vel
self.patch = pl.Circle(self.pos, self.radius, fc = 'r')
def pos(self, pos):
self.pos = pos
def vel(self, vel):
self.vel = vel
I can then give this ball a position and velocity when I create the object, e.g. creating a ball which starts at (1,0) moving with velocity (3,0) is created like:
b1 = Ball([1,0], [3,0])
I have a daughter class of this ball object called Container, which is basically just a ball but with a radius of 10 instead, and the velocity and position are fixed at (0,0).
class Container(Ball):
def __init__(self, radius = 10, vel = np.array([0,0]), pos = np.array([0,0])):
self.radius = radius
self.pos = pos
self.vel = vel
Finally, I have a class Simulation, which takes a ball object, and the container object, and simulates the collision of the ball against the container wall.
class Simulation():
def __init__(self, ball = Ball(), container = Container()):
self._container = container
self._ball = ball
self._pos = ball.pos
self._vel = ball.vel
def next_collision(self):
self._vel = self._container.collide(self._ball)
So, self._vel is the velocity of the ball, after it bounces off the wall. Now, I want to make this velocity the new velocity of the ball object, so that when I run the next_collision method again on this ball, it uses the new velocity, rather than the old velocity which I set at the start. So each time I run the next_collision method, it changes the velocity of the ball object to the new velocity calculated by next_collision.
As an example, if the ball is initialised with velocity (3,0), then running the next_collision method should update the ball's velocity to (-3,0). Then, if I run the next_collision method again, it should update the ball's value to (3,0) and so on and so on.
Currently, if I print self._vel, it does tell me the correct new velocity, though it doesn't update the velocity of the ball, so each time I run the next_collision method, it just prints the same velocity over and over again because it is using the same initial conditions.
Also, I didn't post the whole code for each of the classes here, to keep this as succinct as possible. However, i can provide them if nececessary.
Many thanks in advance,
Sid