AttributeError: 'RandomWalk' object has no attribute 'x_step' (Рефакторинг)

Рейтинг: 0Ответов: 1Опубликовано: 09.03.2023
# random_walk.py
from random import choice
class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points
        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.
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step
            self.x_values.append(x)
            self.y_values.append(y)

Сделал рефакторинг (разбил метод fill_walk() на 2 метода - fill_walk и get_step):

# random_walk.py
from random import choice
class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

    def get_step(self):     
        while len(self.x_values) < self.num_points:
            x_direction = choice([1,-1])
            y_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            y_distance = choice([0, 1, 2, 3, 4])
            self.x_step = x_direction * x_distance
            self.y_step = y_direction * y_distance

    def fill_walk(self):
        while len(self.x_values) < self.num_points:

            if self.x_step == 0 and self.y_step == 0:
                continue
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step
            self.x_values.append(x)
            self.y_values.append(y)

Запускаю случайное блуждание:

import matplotlib.pyplot as plt
from random_walk import RandomWalk


rw = RandomWalk(50)
rw.fill_walk()
plt.style.use('classic')
fig, ax = plt.subplots()
point_numbers = range(rw.num_points)
ax.plot(rw.x_values, rw.y_values, linewidth=1)
plt.show()

выдает ошибку:

Traceback (most recent call last):
  File "C:\Users\user\Desktop\python\trt.py", line 7, in <module>
    rw.fill_walk()
  File "C:\Users\user\Desktop\python\random_walk.py", line 45, in fill_walk
    if self.x_step == 0 and self.y_step == 0:
       ^^^^^^^^^^^
AttributeError: 'RandomWalk' object has no attribute 'x_step'

Ответы

▲ 0

Причины ошибки в том, что x_step и y_step создаются в методе get_step, т.е. пока вы не вызовите этот метод, этих атрибутов не существует.

А т.к. в первой версии x_step меняется на каждой итерации, то в цикле внутри fill_walk каждый раз надо вызывать get_step():

def fill_walk(self):
    while len(self.x_values) < self.num_points:
        self.get_step()
        ...