I have the following code:
class random_walk:
#ns: number of steps
#np: number of particles
#dimension : choose between 1D or 2D
def __init__(self,ns,np,dimension=None):
self.ns=ns
self.np=np
self.dimension=dimension
if self.dimension==2:
#--- These represent the orientation of movement ------------
step=random.choice([[0, 1], [1, 0], [0, -1], [-1, 0]])
def step2d(self,ns):
return [step for i in range(ns)]
#steps=table with trajectories that constitute from m steps
def steps(self,ns):
return 2*sc.random.random_integers(0,1,size=self.ns)-1
If I do rw=random_walk(ns,np) and then rw.steps(ns) it works ok.
But if I try rw=random_walk(ns,np,dimension) and then rw.step2d(ns) it gives me: random_walk instance has no attribute 'step2d'.
As far as I understand, it is because the step2d function is in the init method. Is there a way to access it?
Thank you!
Yes, you need to actually put the
step2d()method on the class, not in the__init__()method. Python does let you add a method to your instance dynamically, so you could define it in__init__()like you have and then add it to the instance if the dimensionality is 2, but it is kind of hairy since you also need to create a bound method wrapper for it or it won’t work right. It is also a bad design and will be confusing to other programers who look at your code. So don’t do it that way.Instead, either:
Have a distinct subclass for 2D objects that has the
step2d()method. You can have a factory function that returns an instance of the proper class depending on the dimensionality (or implement the factory as part of the base class’s__new__()).Simply define
step2d()as another method; checkself.dimensionright at the top and raiseTypeErrorif dimensionality is not 2. Like so: