各位,我遇到了这个错误能指导一下我吗?
'RandomWalk' object has no attribute 'x_values'
from random import choice
class RandoWalk():
"""一个生成随机漫步数据的类"""
def __init__(self,num_points = 500):
self.nun_points = num_points
#所有随机漫步都始于(0,0)
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 == 0and y_step == 0:
continue
#计算下一个点的x和y
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + t_step
self.x_values.append(next_x)
self.y_balues.append(next_y)
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s = 15)
plt.show()
最后报错现实这个错误
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [46], in 2>()
1 rw = RandomWalk()
----> 2 rw.fill_walk()
3 plt.scatter(rw.x_values,rw.y_values,s = 15)
4 plt.show()
Input In [17], in RandomWalk.fill_walk(self)
3 """计算随机漫步包含的所有点"""
4 #不断漫步,直到列表达到指定长度
----> 5 while len(self.x_values) < self.num_points:
6 #决定前进方向以及距离
7 x_direction = choice([1,-1])
8 x_distance = choice([0,1,2,3,4])
AttributeError: 'RandomWalk' object has no attribute 'x_values'
|
报错是说RandomWalk需要定义变量 x_values;
看了代码有2个主要问题,1未定义变量,2语法错误变量名引用错误,修改后可正常绘制随机漫步散点图;
如图
# 随机漫步demo
from random import choice
from matplotlib import pyplot as plt
class RandomWalk():
"""一个生成随机漫步数据的类"""
num_points = 0
x_values = []
y_values = []
def __init__(self, num_points=500):
self.num_points = num_points
# 所有随机漫步都始于(0,0)
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
# 计算下一个点的x和y
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()