python类中方法相互调用_python 类中方法之间的调用
代碼為《python從入門到實踐》習題15-5的解答from random import choice
class RandomWalk():
"""一個生成隨機漫步數據的類"""
def __init__(self, num_points=5000):
"""初始化隨機漫步的屬性"""
self.num_points = num_points
# 所有隨機漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
self.direction = None # 當此行消失時,代碼仍有效
self.distance = None # 當此行消失時,代碼仍有效
def get_step(self):
self.direction = choice([1, -1])
self.distance = choice([0, 1, 2, 3, 4])
return self.direction*self.distance
def fill_walk(self):
"""計算隨機漫步包含的所有點"""
# 不斷漫步,直到列表到達指定的長度
while len(self.x_values) < self.num_points:
# 決定前進方向以及沿這個方向移動的距離
x_step = self.get_step() # 這里一定要加上self. 不然會報錯
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)
以上代碼,相當于對下面代碼的重構:from random import choice
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_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值
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)
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python类中方法相互调用_python 类中方法之间的调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pandas合并groupby_Pand
- 下一篇: java 重建二叉树_【剑指offer】