Classes 3

1 __init()__ Method

A better way to setup your class is by including an __init()__ method that will be called whenever you create an instance. This way you can update or add features that apply only to the instance.

class CParticle1D:
    # Class variables
    mass=None
    position=None
    radius=None

    def __init__(self, position) -> None:
        # Object variables
        self.position = position
        pass

Things can get a bit confusing here because there is a distinction between class and object variables. - mass, position and radius are class variables. There is another variable position that belongs only to the object. - When you want to access the object variable position use self.position. There are also variables mass and radius avaialbe to the object. If you change these (e.g. self.mass=10) then the class variable and object variables will have different values.

2 Methods

You can also create functions (technically called methods) that operate on your objects.

In the code below I have included a method called move().

class CParticle1D:
    # Class variables
    mass = None
    position = None
    radius = None

    def __init__(self, position) -> None:
        # Object variables
        self.position = position
        pass

    def move(self, displacement):
        self.position += displacement

You use move() like:

particle = CParticle1D(position=10)
particle.move(3)
print(f'{particle.position=}')
particle.position=13

Please note that the definition of move() must contain self. This will be automatically supplied by Python when you call the method.

Back to top