首页 新闻 会员 周边

重构函数失败

0
悬赏园豆:10 [待解决问题]

我把类中的一个方法中的部分代码放到一个另一个方法中,然后用这个方法调用那个方法,一直说我未定义,大神帮忙看看哪里出了问题。
import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
'''一个生成随机漫步数据的类'''
def init(self,num_points):
self.num_points = num_points
#所有的随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
self.step = 0
def get_step(self):
direction = choice([1, -1]) # 随机选择向左向右两个方向
distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8]) # 随机选择移动的距离
self.step = direction * distance # 每次移动的步长
def fill_walk(self):
'''定义一个循环,直到达到给定的点数'''
while len(self.x_values) < self.num_points:
x_step = get_step()
y_step = get_step()
#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 and y_step == 0:
continue
#计算下一个点的xy值,用列表的最后一个值加上步长
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)

Charlie大夫的主页 Charlie大夫 | 初学一级 | 园豆:176
提问于:2018-11-14 19:45
< >
分享
所有回答(1)
0

我运行了你的代码,没有报错耶。
你那边报错内容是什么?

import matplotlib.pyplot as plt
from random import choice

class RandomWalk():
    '''一个生成随机漫步数据的类'''
    def init(self,num_points):
        self.num_points = num_points
        #所有的随机漫步都始于(0,0)
        self.x_values = [0]
        self.y_values = [0]
        self.step = 0
        
    def get_step(self):
        direction = choice([1, -1]) # 随机选择向左向右两个方向
        distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8]) # 随机选择移动的距离
        self.step = direction * distance # 每次移动的步长
        
    def fill_walk(self):
        '''定义一个循环,直到达到给定的点数'''
        while len(self.x_values) < self.num_points:
            x_step = get_step()
            y_step = get_step()
            #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 and y_step == 0:
                continue
                #计算下一个点的xy值,用列表的最后一个值加上步长
                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)
芽衣 | 园豆:384 (菜鸟二级) | 2018-11-15 17:41
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册