Python学习:面向对象,类的设计(1)

简单运用以下random里面的函数,然后将数据可视化出来.

[0]以下是模拟一个人每次随机往四个方向走一步,然后得到走steps步后的距离原来位置的距离.

from pylab import *
import random,math
class Drunk_person:
    __possible_dir = ('north','west','east','south')
    __Possibles = {'north':(0,1),'west':(-1,0),'east':(1,0),'south':(0,-1)}
    def __init__(self):
        self.x,self.y = 0,0
    @property
    def pos(self):
        return (self.x,self.y) 
    def move(self,direction):
        try:
            self.x += self.__Possibles[direction][0]
            self.y += self.__Possibles[direction][1]
        except KeyError: 
            print('there is not direction:%s'% direction)
            raise KeyError
    @property
    def distance(self):
        temp = self.x**2+self.y**2
        return math.sqrt(temp)
    def random_trials(self,steps = 10000):
        D = []
        for i in range(steps):
            self.move(random.choice(self.__possible_dir))
            D.append(self.distance)
        return D
def Addlabels_toGraph(titles = '',axises = [],xlabels = '',ylabels = ''):
    title(title)
    xlabel(xlabel)
    ylabel(ylabel)
    if(axises!=[]): axis(axises)

d = Drunk_person()
distance_list = d.random_trials(3000)
Addlabels_toGraph('sss')
plot(distance_list,'ro')
print(d.pos)
show()

plot所需要的模块是pylab,是matlab中引用的模块,直接用pip命令安装一个就ok了.会自动帮你安装好所有需要的模块.超级方便.

然后把plot需要的一些命令写成一个函数,方便运用.

random.choice的作用是从给出的序列中随机选择一个.

再看看直方图:bins参数是用来确定分为多少个图的.

a = [1,2,3,4,5,6]
d = []
for i in range(10000):
    d.append(random.choice(a)+random.choice(a))
hist(d,bins = 11)
show()

你可能感兴趣的:(Python学习:面向对象,类的设计(1))