定义的函数在调用时抛出 "not defined" NameError

Defined function throwing a "not defined" NameError when called

我正在尝试通过 plotly 重新创建一个使用 matplotlib 的绘图,每当我调用我的函数时,我都会收到一条错误消息,

Traceback (most recent call last):
  File "c:\Users\gramb\python_projects\project_2\rw_plotly\random_walk_p.py", line 38, in <module>
    rw.fill_walk()
  File "c:\Users\gramb\python_projects\project_2\rw_plotly\random_walk_p.py", line 20, in fill_walk
    x_step, y_step = _get_step(), _get_step()
NameError: name '_get_step' is not defined

虽然函数是这样写的 class:

    def __init__(self, num_points=5000):
        """Initialize attributes of a walk."""
        self.num_points = num_points

        # Walks start at (0, 0).
        self.x_values = [0]
        self.y_values = [0]
    
    def fill_walk(self):
        """Calculates all points of the walk."""

        # Take steps until max length
        while len(self.x_values) < self.num_points:
            # Decide direction and distance    
            x_step, y_step = _get_step(), _get_step()

            # Start loop from top if both are 0
            if x_step == 0 and y_step == 0:
                continue
            
            # Calculate new position
            x, y = self.x_values[-1] + x_step, self.y_values[-1] + y_step

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

    def _get_step(self):
        """Creates a step on the walk."""
        direction = choice([1, -1])
        distance = choice(range(5))
        return direction * distance

rw = RandomWalk()
rw.fill_walk()

直到我用 pip 安装 pandas 之后才出现错误,但我也卸载了它以确保这不是问题,但问题仍然存在。

我正在使用 VS Code 和 python 的一些扩展,因此如果需要该信息,请告诉我。

您需要使用 self._get_step 而不仅仅是 get_step。这将运行 class.

实例下的函数

您在 class 中定义了 _get_step 方法,因此要在 class 中调用当前实例方法,您必须使用 self._get_step()