library(reticulate)
use_python("/Users/chammika/miniconda3/envs/science-work/bin/python", required = TRUE)Classes 3
__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
passThings 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.
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 += displacementYou 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.