没有得到属性错误,属性似乎在那里?

时间:2018-12-20 01:11:19

标签: 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>
    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'

找出导致错误的原因

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()

1 个答案:

答案 0 :(得分:2)

正如@melpomene所说,构造函数每侧需要两个下划线。

__init__(self, num_points=5000):
    ...

__init__是保留方法,在对象创建时调用。但是,永远不会调用您的初始化方法,即每侧只有一个下划线。因此,该对象永远不会获得x_values作为属性。