无法让Python从同一目录中的文件导入类

时间:2020-07-22 18:53:50

标签: python oop

我正在尝试将一个类从一个文件导入到同一目录中的另一个文件,但是我似乎无法让python看到我编写的另一个文件。我正在尝试将我在random_walk.py文件中编写的RandomWalk类导入到rw_visual.py文件中。但是我得到了ImportError:尝试相对导入,没有已知的父程序包。任何帮助,将不胜感激。我从random_walk导入RandomWalk中获取错误

random_walk.py:

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]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:

            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            if x_step == 0 and y_step == 0:
                continue

            # adds the _steps to the current position of the walk
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            self.x_values.append(x)
            self.y_values.append(y)

rw_visual:

import matplotlib.pyplot as plt

from .random_walk import Randomwalk

rw = Randomwalk()
rw.fill_walk()

plt.style.use('classic')

fig, ax = plt.subplots()

ax.scatter(rw.x_values, rw.y_values, s=15)

plt.show()

1 个答案:

答案 0 :(得分:1)

在您的目录中添加空的__init__.py

相关问题