Python 没有属性错误,属性似乎存在?
我已经把这段代码读了很多遍了,但似乎不知道我做错了什么。我试图在matplotlib中创建一个随机游动。我创建了一个带有随机游走功能的文件,以及一个用于运行代码和绘制点的文件。我收到一个错误,上面写着:Python 没有属性错误,属性似乎存在?,python,python-3.x,attributeerror,Python,Python 3.x,Attributeerror,我已经把这段代码读了很多遍了,但似乎不知道我做错了什么。我试图在matplotlib中创建一个随机游动。我创建了一个带有随机游走功能的文件,以及一个用于运行代码和绘制点的文件。我收到一个错误,上面写着: Traceback (most recent call last): File "/Users/kevinayers/Desktop/Python/CrashCourse/Python_Vizualization/rw_visual.py", line 8, in <module>
Traceback (most recent call last):
File "/Users/kevinayers/Desktop/Python/CrashCourse/Python_Vizualization/rw_visual.py", line 8, in <module>
rw.fill_walk()
File "/Users/kevinayers/Desktop/Python/CrashCourse/Python_Vizualization/random_walk.py", line 18, in fill_walk
while len(self.x_values) < self.num_points:
AttributeError: 'RandomWalk' object has no attribute 'x_values'
回溯(最近一次呼叫最后一次):
文件“/Users/kevinayers/Desktop/Python/CrashCourse/Python_vizalization/rw_visual.py”,第8行,在
rw.填充_walk()
文件“/Users/kevinayers/Desktop/Python/CrashCourse/Python_-vizalization/random_-walk.py”,第18行,在fill_-walk中
而len(self.x_值)
找出导致错误的原因
from random import choice
class RandomWalk():
"""A class to generate random walks."""
def _init_(self, num_points=5000):
""" Initialize attributes of a walk."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in the walk."""
# Keep taking steps until the walk reaches the desired length
while len(self.x_values) < self.num_points:
# Decide which direction to go and how far to go in that direction
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
# Reject moves that go nowhere
if x_step == 0 and y_step == 0:
continue
# Calculate the next x and y values
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
from random_walk import RandomWalk
# Make a random walk, and plot the pointsself.
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
来自随机导入选择
类RandomWalk():
“”“生成随机游动的类。”“”
定义初始值(自我,点数=5000):
“”“初始化漫游的属性。”“”
self.num\u points=num\u points
self.x_值=[0]
self.y_值=[0]
def加注口(自行):
“”“计算行走中的所有点。”“”
#继续采取步骤,直到步行达到所需长度
而len(self.x_值)
正如@melpomene已经说过的,构造函数的每一面需要两个下划线
__init__(self, num_points=5000):
...
\uuuu init\uuuu
是一个保留方法,在创建对象时调用。但是您的init方法(每边只有一条下划线)永远不会被调用。因此,对象永远不会将x\u值
作为属性。\uuuu init\uuuu
,而不是\uu init\uu
。