[英]Can't get Python to import a class from file in the same directory
我正在尝试将 class 从一个文件导入到同一目录中的另一个文件,但我似乎无法让 python 看到我编写的另一个文件。 我正在尝试将我在 random_walk.py 文件中编写的 RandomWalk class 导入到 rw_visual.py 文件中。 但是我得到 ImportError:尝试相对导入,没有已知的父 package。 任何帮助,将不胜感激。 我在 from random_walk import 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()
在您的目录中添加空的__init__.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.