15-5 重构:方法 fill_walk()很长。请新建一个名为 get_step()的方法,用于确定每次漫步的距离和方向,并计算这次漫步将如何移动。然后,在 fill_walk()中调用 get_step()两次:
x_step = self.get_step()
y_step = self.get_step()
通过这样的重构,可缩小 fill_walk()的规模,让这个方法阅读和理解起来更容易。
random_walk.py
from random import choice
class RandomWalk():
"""一个生成随机漫步数据的类"""
def __init__(self,num_points=500):
"""初始化随机漫步的属性"""
self.num_points = num_points
# 所有随机漫步都始于(0, 0)
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""确定每次漫步的距离和方向"""
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
step = direction * distance
return step
def fill_walk(self):
"""计算随机漫步包含的所有点"""
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
# 拒绝原地踏步
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)
在 get_step()方法的最后一行一定要用 return 返回值,否则报错