Python - Importing classes to another module

70 Views Asked by At

I have just started to learn Python and I am now practicing with the Python Crash Course book. I have to plot some points on a chart simulating a random walk, in order to do so, after importing matplotlib, I wrote the following code in a module:

from random import choice
class RandomWalk():
    def __init__(self,num_points=5000):
        self.num_points=num_points
        self.x_values=[0]
        self.y_values=[0]
  • I wrote the code to indicate in which range to move on x and y for each step, but that part of the code shouldn't be relevant for this question.

Then the book suggest to plot the random walk by calling my class from another module, with the following code:

from random_walk import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15) 
plt.show()

However, this code doesn't work:

ModuleNotFoundError                       Traceback (most recent call last)
Input In [9], in <cell line: 1>()
----> 1 from random_walk import RandomWalk
      2 rw = RandomWalk()
      3 rw.fill_walk()

ModuleNotFoundError: No module named 'random_walk'

Since I put the two module in the same folder, I don't get why Python does not find my module. The module from which I am trying to call the class is called "random_walk.ipynb".

Do you have any suggestions?

Thanks!!!

1

There are 1 best solutions below

0
Redox On

Looks like you are using jupyter notebook. So, you should be using this command in place to from random_walk..... More information here

%run random_walk.ipynb

This will include the class in that file. Hope this is what you are looking for.