AttributeError: 'RandomWalk' object has no attribute 'xvalue
python吧
全部回复
仅看楼主
level 4
虽然显示属性错误,但是类中明明有这个属性,有点不知为何了,百度过了没有找到答案。下面贴代码。
import matplotlib.pyplot as plt
from random import choice
class RandomWalk:
def _init_(self, points):
self.xvalue = [0]
self.yvalue = [0]
self.points = points
def walk(self):
x_direction = choice([1, -1])
y_direction = choice([1, -1])
x_distance = choice(range(5))
y_distance = choice(range(5))
next_x = x_distance * x_direction
next_y = y_distance * y_direction
self.xvalue.append(next_x)
self.yvalue.append(next_y)
rw = RandomWalk()
rw.points = 100
for i in range(rw.points):
rw.walk()
plt.scatter(rw.xvalue, rw.yvalue, s=15)
plt.show()
2018年09月09日 02点09分 1
level 9
初始化函数是__init__,不是_init_
2018年09月09日 06点09分 2
谢谢,确实是这个原因
2018年09月09日 08点09分
@贴吧用户_0JMK2AA 我也正找不出原因来,非常感谢
2018年11月22日 05点11分
兄弟,你看看我的帖子,我也是attribute error但是我init没啥问题啊,救命啊[泪]
2018年11月22日 07点11分
牛逼
2019年05月01日 08点05分
level 4
哈哈,我也遇到拉
2018年10月30日 01点10分 3
level 4
兄弟,你看看我的帖子,我也是attribute error但是我init没啥问题啊,救命啊[泪]
2018年11月22日 07点11分 4
+1,老哥你的问题解决了没,求指导是什么原因导致的啊,我也卡住了
2019年02月21日 03点02分
检查下def有没有缩进
2019年04月13日 09点04分
level 1
有可能是你的xvalue写错了,仔细看看有没有事单词写错
2019年04月22日 08点04分 5
level 1
还有一种笨方法就是:找到源代码,然后一句一句的赋值你原来写的代码,一直到有错误出现再看是不是自己哪里写错或格式有问题
2019年04月22日 09点04分 6
level 1
init 是双下划线
2019年07月16日 08点07分 7
感谢!我就是这样改好了
2020年07月20日 05点07分
感谢!我也是这样改好的
2021年12月23日 01点12分
level 2
我在学习中也遇到了这个问题,解决后的程序如下:
from random import choice
class Random_walk:
def __init__(self):
self.num_points = 500
self.x_values = []
self.y_values = []
def fill_walk(self):
x = self.num_points
while len(self.x_values) < int(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
elif self.x_values == [] or self.y_values == []:
self.x_values.append(x_step)
self.y_values.append(y_step)
else:
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)
import matplotlib.pyplot as plt
rw = Random_walk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=25)
plt.show()
2019年10月14日 23点10分 9
level 2
区别在于把例子中的def __init__(self,num_points=500):改为def __init__(self):
2019年10月14日 23点10分 11
level 1
把walk方法放到RandomWalk类下面,而不是平行结构
2020年04月28日 14点04分 12
level 7
RandomWalk里面没有xvalue,看看RandomWalk的xvalue是否赋值了
2020年09月13日 11点09分 13
1