Can';t让Python从同一目录中的文件导入类
我试图将一个类从一个文件导入同一目录中的另一个文件,但我似乎无法让python看到我编写的另一个文件。我正在尝试将我在random_walk.py文件中编写的RandomWalk类导入rw_visual.py文件。但是我得到了ImportError:在没有已知父包的情况下尝试了相对导入。任何帮助都将不胜感激。我在“从随机漫步导入随机漫步”中得到错误 随机_walk.py:Can';t让Python从同一目录中的文件导入类,python,oop,Python,Oop,我试图将一个类从一个文件导入同一目录中的另一个文件,但我似乎无法让python看到我编写的另一个文件。我正在尝试将我在random_walk.py文件中编写的RandomWalk类导入rw_visual.py文件。但是我得到了ImportError:在没有已知父包的情况下尝试了相对导入。任何帮助都将不胜感激。我在“从随机漫步导入随机漫步”中得到错误 随机_walk.py: from random import choice class RandomWalk: def __init__(
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)
在目录中添加空的
\uuuu init\uuuuuuuuuupy
,python需要一个\uu init\uuupy
(双下划线)文件才能将其识别为模块。尝试添加一个空的init文件。不幸的是,它不起作用。我将一个空init.py添加到与其他两个文件相同的目录中。它可能是一个子目录吗?是的,你确实需要一个子目录。在一个目录中,您可以使用rw_visual,但random_walk和init文件需要同时位于一个目录中。我当前将这三个文件都位于同一目录中,是否应将rw_visual移动到新目录中?是的,与init一起移动。
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()