|
一个随机游走的函数正常运行是没问题的。然后把里面的一个函数挪出来了,结果再加就变成了类型错误int和none不能相加了。
'''这是重构后不能调用的'''
class Randomwalk():
'''一个生成随机漫步数据的类'''
def __init__(self, num_points=5000):
'''初始化随机漫步属性'''
self.num_points = num_points
#所有的随机漫步都从(0,0)开始
self.x_values = [0]
self.y_values = [0]
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)
def get_step(self):
x_direction = choice([1,-1])
x_distance = choice([0,1,2,3,4,5,6,7,8])
x_step = x_direction * x_distance
y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4,5,6,7,8])
y_step = y_direction * y_distance
'''这是重构前没问题的'''
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,5,6,7,8])
x_step = x_direction * x_distance
y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4,5,6,7,8])
y_step = y_direction * y_distance
#拒绝原地踏步
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)
|
-
|