我想用pygal绘制随机漫步点
并存储了一个svg文件
在run.py中我尝试使用循环,每个循环1次制作一些数据,并赋值变量
我的代码:
random_walk.py
from random import choice
class RandomWalk():
def __init__(self, num_points=10240):
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
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)
run.py
import pygal
from random_walk import RandomWalk
xy_sjmb = pygal.XY(stroke=False)
xy_sjmb.title = "random rambled"
a, b, c, d = [], [], [], []
all =[a, b, c, d]
for i in range(len(all)):
rw = RandomWalk()
rw.fill_walk()
ns =[(j, k) for j, k in (self.x_values, self.y_values) ]
all[i-1] = ns
xy_sjmb.add('a', a)
xy_sjmb.add('b', b)
xy_sjmb.add('c', c)
xy_sjmb.add('d', d)
xy_sjmb.render_to_file('sjmb.svg')
但有错误: NameError:名称'self'未定义
答案 0 :(得分:1)
将ns =[(j, k) for j, k in (self.x_values, self.y_values) ]
更改为ns =[(j, k) for j, k in (rw.x_values, rw.y_values) ]
。
self
用于引用该对象内部的对象。但在外部,您需要使用指向它的变量来引用该对象。