8 Python编程:从入门到实践---类
示例:
class Restaurant: def __init__(self,restaurant_name,cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(f"The restaurant_name is {self.restaurant_name}") print(f"The cuisine_type is {self.cuisine_type}") def open_restaurant(self): print(f"The {self.restaurant_name} is {self.cuisine_type}") def restaurant(self): print(f"当前就餐人数{self.number_served}") def set_number_served(self,numberq): self.number_served = numberq def increment_number_served(self,numbera): self.number_served += numbera test = Restaurant('hhhh','open') test.describe_restaurant() test.open_restaurant() test.set_number_served(10) test.increment_number_served(20) test.restaurant()
随机漫步示例讲解
from random import choice class Randomwalk(): """生成一个随机漫步的类""" def __init__(self,num_points=5000): 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 if x_step == 0 and y_step == 0: continue 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) return(self.x_values,self.y_values)
逻辑:1、首先引用模块,random的choice方法,choice方法是从一个列表、元组或字符串中的随机项。
2、定义一个Randomwalk的类,默认调用init方法生成一个num_points变量为5000.也就是如果不指定num_points变量,则下面循环会循环5000次
3、定义一个fill_walk函数,如果列表长度小于num_points,就进行循环,x_direction用来定义左右,x_distance用来定义步长。
y_direction用来定义上下,y_distance用来定义步长.如果原地踏步则跳过本次循环
4、移动的点位置记录,为列表最后一个值加上步长
5、将内容增加到列表中
不积跬步,无以至千里;不积小流,无以成江海。