Python 调用时抛出“未定义”名称错误的已定义函数
我试图通过plotly重新创建一个使用matplotlib的绘图,每当调用函数时,我都会发现一个错误:Python 调用时抛出“未定义”名称错误的已定义函数,python,matplotlib,plotly,nameerror,Python,Matplotlib,Plotly,Nameerror,我试图通过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\p
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
当函数在其类中编写时:
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之后才发生,但我也卸载了它,以确保问题还没有出现。
我正在使用带有一些python扩展的VS代码,因此如果需要这些信息,请告诉我。您需要使用self。\u get\u step而不是get\u step。这将在类的实例下运行函数。您在类内定义了_get_步骤方法,因此要在类内调用当前实例方法,您必须使用self。_get_步骤self。_get_步骤与熊猫的安装无关