最近在學習Python從入門到實踐這本書,在做資料可視化的案例時候遇到了一點問題,要生存一個隨機漫步資料的類,然后創建實體,不明白下面為什么rw=RandomWalk() 這里可以不用給實參?請各位大神幫幫忙,謝謝!
#15.3.1 創建RandomWalk()類
from random import choice
class RandomWalk():
"""一個生成隨機漫步資料的類"""
def __init__(self,num_points=5000):
"""初始化隨機漫步的屬性"""
self.num_points = num_points
self.x_values= [0] # 所有隨機漫步都始于(0, 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)
# 創建一個RandomWalk實體,并將其包含的點都繪制出來
rw = RandomWalk() #為什么RandomWalk實體不用給實參的?
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
uj5u.com熱心網友回復:
因為 RandomWalk 類 init 里面 num_points 已經賦值為5000了,不需要再傳參了,你如果要傳參的話可以修改代碼如下:
from random import choice
import matplotlib.pyplot as plt
class RandomWalk():
"""一個生成隨機漫步資料的類"""
def __init__(self, num_points):
"""初始化隨機漫步的屬性"""
self.num_points = num_points
self.x_values = [0] # 所有隨機漫步都始于(0, 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)
# 創建一個RandomWalk實體,并將其包含的點都繪制出來
rw = RandomWalk(5000) # 傳參賦值給num_points
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/285009.html
上一篇:lingo混合整數線性規劃編程
下一篇:jenkins運行python提示ModuleNotFoundError: No module named 'pytest'
