Python 对象编程
对象存在状态,它拥有一组变量/属性和函数。将对象想象成一个盒子,则在盒子里面存放着一些变量来定义这个对象的状态,并且里面通常还会有一些函数,它们则告诉我们这个对象可以做什么!
# Import statements
import numpy
import car# Declare initial variables
# Create a 2D world of 0's
height = 4
width = 6
world = np.zeros((height, width))# Define the initial car state
initial_position = [0, 0] # [y, x] (top-left corner)
velocity = [0, 1] # [vy, vx] (moving to the right)
4.创建并可视化一个Car 对象
# Create a car object with these initial params
carla = car.Car(initial_position, velocity, world)# Display the world
carla.display_world()
输出:
5.命令Car 对象移动
6.学习使用Car Object
1) 导入必要的库
import numpy as np
import car
%matplotlib inline
2) 定义变量初始值
# Create a 2D world of 0's
height = 4
width = 6
world = np.zeros((height, width))# Define the initial car state
initial_position = [0, 0] # [y, x] (top-left corner)
velocity = [0, 1] # [vy, vx] (moving to the right)
3) 创建一个Car Object
# Create a car object with these initial params
carla = car.Car(initial_position, velocity, world)print('Carla\'s initial state is: ' + str(carla.state))
输出:
Carla's initial state is: [[0, 0], [0, 1]]
4) Move 和追踪状态
# Move in the direction of the initial velocity
carla.move()
# Track the change in state
print('Carla\'s state is: ' + str(carla.state))
# Display the world
carla.display_world()
输出:
Carla's state is: [[0, 1], [0, 1]]
5) 使用 move() 和 turn_left() 实现以正方形路径移动,下面是我的实现:
## TODO: Make carla traverse a 4x4 square path
## Display the result
# move to start position
carla.turn_left()
carla.turn_left()
carla.move()# path
for i in range(4):carla.turn_left()for i in range(3):carla.move()
print('Carla\'s state is: ' + str(carla.state))
carla.display_world()
输出:
Carla's state is: [[0, 0], [0, -1]]
7.重要内容:Car Class (Car 类)
8.car.py 文件的一些解释
Animal类继承了object对象,拥有了好多可操作对象,这些都是类中的高级特性。
1) class Car(object): 这看起来有点类似函数声明,但是关键字class 让Python 知道接下来的代码应该要描述一个Car 对象的状态和功能, 也即Car 对象的Variables 和 functions.
import matplotlib.pyplot as plt
""" The Car class defines a car's movement and keeps track of its state.The class includes init, move, and display functions.This class assumes a constant velocity motion model and the stateof the car includes the car's position, and it's velocity.Attributes:state: A list of the car's current position [y, x] and velocity [vy, vx]world: The world that the car is moving within (a 2D list)
"""
class Car(object):# Car constructor# Called when you write car.Car(_, _, _)def __init__(self, position, velocity, world):"""Initializes Car with some position, velocity, and a world to traverse."""# Initialize the state# Position is a list [y, x] and so is velocity [vy, vx]self.state = [position, velocity]self.world = world # world is a 2D list of values that range from 0-1# Set the default colorself.color = 'r'# Initalize the pathself.path = []self.path.append(position)# Move functiondef move(self, dt=1):""" The move function moves the car in the direction of the velocity andupdates the state.It assumes a circular world and a default dt = 1 (though dt can be anynon-negative integer)."""height = len(self.world)width = len(self.world[0])position = self.state[0]velocity = self.state[1]# Predict the new position [y, x] based on velocity [vx, vy] and time, dtpredicted_position = [(position[0] + velocity[0]*dt) % height, # default dt = 1(position[1] + velocity[1]*dt) % width]# Update the stateself.state = [predicted_position, velocity]# Every time the robot moves, add the new position to the pathself.path.append(predicted_position)# Turn left functiondef turn_left(self):""" Turning left "rotates" the velocity values, so vy = -vx, and vx = vy.For example, if a car is going right at 1 world cell/sec this meansvy = 0, vx = 1,and if it turns left, then it should be moving upwards on the world gridat the same speed!And up is vy = -1 and vx = 0"""# Change the velocityvelocity = self.state[1]predicted_velocity = [-velocity[1],velocity[0]]# Update the state velocityself.state[1] = predicted_velocity# Helper function for displaying the world + robot position# Assumes the world in a 2D numpy array and position is in the form [y, x]# path is a list of positions, and it's an optional argumentdef display_world(self):# Store the current position of the carposition = self.state[0]# Plot grid of values + initial ticksplt.matshow(self.world, cmap='gray')# Set minor axes in between the labelsax=plt.gca()rows = len(self.world)cols = len(self.world[0])ax.set_xticks([x-0.5 for x in range(1,cols)],minor=True )ax.set_yticks([y-0.5 for y in range(1,rows)],minor=True)# Plot grid on minor axes in gray (width = 2)plt.grid(which='minor',ls='-',lw=2, color='gray')# Create a 'x' character that represents the car# ha = horizontal alignment, va = vericalax.text(position[1], position[0], 'x', ha='center', va='center', color=self.color, fontsize=30)# Draw path if it existsif(len(self.path) > 1):# loop through all path indices and draw a dot (unless it's at the car's location)for pos in self.path:if(pos != position):ax.text(pos[1], pos[0], '.', ha='center', va='baseline', color=self.color, fontsize=30)# Display final resultplt.show()
9.修改car.py文件
# Turn left function
def turn_left(self):""" Turning left "rotates" the velocity values, so vy = -vx, and vx = vy.For example, if a car is going right at 1 world cell/sec this meansvy = 0, vx = 1,and if it turns left, then it should be moving upwards on the world gridat the same speed!And up is vy = -1 and vx = 0"""# Change the velocityvelocity = self.state[1]predicted_velocity = [-velocity[1],velocity[0]]# Update the state velocityself.state[1] = predicted_velocity## TODO: Write the turn_right function
## Hint: Use turn_left for inspiration!
def turn_right(self):velocity = self.state[1]predicted_velocity = [ velocity[1], -velocity[0] ]self.state[1] = predicted_velocity
保存car.py 文件的修改之后,我们就能使用turn_right() 函数了,由于是模仿turn_left书写的,因而调用格式和 turn_left 完全一致 。
10.增加Color
我们知道,在上面的car.py 文件中,__init__是这样定义的:
def __init__(self, position, velocity, world):"""Initializes Car with some position, velocity, and a world to traverse."""# Initialize the state# Position is a list [y, x] and so is velocity [vy, vx]self.state = [position, velocity]self.world = world # world is a 2D list of values that range from 0-1# Set the default colorself.color = 'r'# Initalize the pathself.path = []self.path.append(position)
- 使用传入参数初始化: 这类Variable在__init__下赋值时,使用的值为 def __init__(self, position, velocity, world) 括号内传入的参数。如self.state = [position, velocity]
- 使用默认值初始化: 这类Variable在__init__下直接赋初始值,如self.color = 'r'
def __init__(self, position, velocity, world, color):"""Initializes Car with some position, velocity, and a world to traverse."""# Initialize the state# Position is a list [y, x] and so is velocity [vy, vx]self.state = [position, velocity]self.world = world # world is a 2D list of values that range from 0-1# Set the colorself.color = color# Initalize the pathself.path = []self.path.append(position)
3) 特别需要说明的是,使用传入参数初始化和使用默认值初始化是可以共存的!如这样修改 def __init__ 语句:
def __init__(self, position, velocity, world, color='r'):
这时候,若创建Car对象的时候,没有传入color参数,则创建Car对象的时候会使用默认的color值'r';若传入color参数,则创建对象的时候会使用传入的值。这个内容在”11.实例化多个Car对象“中会体现有所体现,只不过这个时候的变量是新加入的maximum_speed。
import matplotlib.pyplot as plt
""" The Car class defines a car's movement and keeps track of its state.The class includes init, move, and display functions.This class assumes a constant velocity motion model and the stateof the car includes the car's position, and it's velocity.Attributes:state: A list of the car's current position [y, x] and velocity [vy, vx]world: The world that the car is moving within (a 2D list)
"""
class Car(object):# Car constructor# Called when you write car.Car(_, _, _)def __init__(self, position, velocity, world, color = 'r', maximum_speed = 160):"""Initializes Car with some position, velocity, and a world to traverse."""# Initialize the state# Position is a list [y, x] and so is velocity [vy, vx]self.state = [position, velocity]self.world = world # world is a 2D list of values that range from 0-1# Set the colorself.color = color# Set the maximum_speedself.maximum_speed = maximum_speed# Initalize the pathself.path = []self.path.append(position)# Move functiondef move(self, dt=1):""" The move function moves the car in the direction of the velocity andupdates the state.It assumes a circular world and a default dt = 1 (though dt can be anynon-negative integer)."""height = len(self.world)width = len(self.world[0])position = self.state[0]velocity = self.state[1]# Predict the new position [y, x] based on velocity [vx, vy] and time, dtpredicted_position = [(position[0] + velocity[0]*dt) % height, # default dt = 1(position[1] + velocity[1]*dt) % width]# Update the stateself.state = [predicted_position, velocity]# Every time the robot moves, add the new position to the pathself.path.append(predicted_position)# Turn left functiondef turn_left(self):""" Turning left "rotates" the velocity values, so vy = -vx, and vx = vy.For example, if a car is going right at 1 world cell/sec this meansvy = 0, vx = 1,and if it turns left, then it should be moving upwards on the world gridat the same speed!And up is vy = -1 and vx = 0"""# Change the velocityvelocity = self.state[1]predicted_velocity = [-velocity[1],velocity[0]]# Update the state velocityself.state[1] = predicted_velocity# Helper function for displaying the world + robot position# Assumes the world in a 2D numpy array and position is in the form [y, x]# path is a list of positions, and it's an optional argumentdef display_world(self):# Store the current position of the carposition = self.state[0]# Plot grid of values + initial ticksplt.matshow(self.world, cmap='gray')# Set minor axes in between the labelsax=plt.gca()rows = len(self.world)cols = len(self.world[0])ax.set_xticks([x-0.5 for x in range(1,cols)],minor=True )ax.set_yticks([y-0.5 for y in range(1,rows)],minor=True)# Plot grid on minor axes in gray (width = 2)plt.grid(which='minor',ls='-',lw=2, color='gray')# Create a 'x' character that represents the car# ha = horizontal alignment, va = vericalax.text(position[1], position[0], 'x', ha='center', va='center', color=self.color, fontsize=30)# Draw path if it existsif(len(self.path) > 1):# loop through all path indices and draw a dot (unless it's at the car's location)for pos in self.path:if(pos != position):ax.text(pos[1], pos[0], '.', ha='center', va='baseline', color=self.color, fontsize=30)# Display final resultplt.show()
创建多个Car 对象的代码如下:
import numpy as np
import car
%matplotlib inline
# Auto-reload function so that this notebook keeps up with
# changes in the class file
%load_ext autoreload
%autoreload 2
定义初始值:
# Create a 2D world of 0's
height = 4
width = 6
world = np.zeros((height, width))
# Define the initial car state
initial_position = [0, 0] # [y, x] (top-left corner)
velocity = [0, 1] # [vy, vx] (moving to the right)
创建两辆颜色不同的车,并且可视化它们的world
[position1, position2] = [[1,1], [3,3]]
[velocity1, velocity2] = [[0,1], [1,0]]
[color1, color2] = ['g', 'y']tokyo = car.Car(position1, velocity1, world, color1) # parameter "maximum_speed" use default value 160
tesla = car.Car(position2, velocity2, world, color2, 120) # parameter "maximum_speed" use value 120tokyo.move()
tesla.move()
tokyo.display_world()
tesla.display_world()print("tokyo's maximum speed is " + str(tokyo.maximum_speed))
print("tesla's maximum speed is " + str(tesla.maximum_speed))
输出:
tokyo's maximum speed is 160
tesla's maximum speed is 120
12.Color 类
import matplotlib.pyplot as plt
'''
The color class creates a color from 3 values, r, g, and b (red, green, and blue).
attributes:r - a value between 0-255 for redg - a value between 0-255 for greenb - a value between 0-255 for blue
'''class Color(object):# __init__ is called when a color is constructed using color.Color(_, _, _)def __init__(self, r, g, b):# Setting the r valueself.r = r## TODO: Set the other two color variables g and bself.g = gself.b = b# __repr__ is called when a color is printed using print(some_color)# It must return a stringdef __repr__(self):'''Display a color swatch and then return a text description of r,g,b values.'''plt.imshow([[(self.r/255, self.g/255, self.b/255)]])## TODO: Write a string representation for the color## ex. "rgb = [self.r, self.g, self.b]"## Right now this returns an empty stringstring = 'rgb = '+ str([self.r, self.g, self.b])return string
创建一个color 对象:
# Notice we are importing the color class!import numpy as np
import color%matplotlib inline
%load_ext autoreload
%autoreload 2
输出:
The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
定义color并将其打印:
# r, g, b
r = 200
g = 0
b = 200
# Create the color object
test_color = color.Color(r, g, b)
# This will throw an error if the class code is incomplete
print(test_color) # automatically call __repr__
输出:
rgb = [[200, 0, 200]]
1 3 .关于重载函数(Overloading Functions), 重载Color Addtion
def __add__(self, other):
# Create an empty list
added_state = []# Add the states together, element-wise
for i in range(self.state):
added_value = self.state[i] + other.state[i]
added_state.append(added_value)return added_state
上面的版本,添加了状态变量!或者你也可以选择只打印添加车辆是无效操作,如下面代码所示。
def __add__(self, other):
# Print an error message and return the unchanged, first state
print('Adding two cars is an invalid operation!')
return self.state
import matplotlib.pyplot as plt
'''
The color class creates a color from 3 values, r, g, and b (red, green, and blue).
attributes:r - a value between 0-255 for redg - a value between 0-255 for greenb - a value between 0-255 for blue
'''
class Color(object):# Initializes a color with rgb valuesdef __init__(self, r, g, b):self.r = rself.g = gself.b = b# Called when a Color object is printed outdef __repr__(self):'''Display a color swatch and returns a text description of r,g,b values'''plt.imshow([[(self.r/255, self.g/255, self.b/255)]])return 'r, g, b = ' + str(self.r) + ', ' + str(self.g) + ', ' + str(self.b)## TODO: Complete this add function to add two colors togetherdef __add__(self, other):'''Adds the r, g, and b components of each color togetherand averaging them.The new Color object, with these averaged rgb values,is returned.'''return Color((self.r+other.r)/2, (self.g+other.g)/2, (self.b+other.b)/2)
导入color:
# Notice we are importing the color class!
import numpy as np
import color
%matplotlib inline
# Auto-reload function so that this notebook keeps up with
# changes in the class file
%load_ext autoreload
%autoreload 2
定义多个颜色并打印:
color1 = color.Color(250, 0, 0)
print(color1)
输出:
color2 = color.Color(0, 50, 200)
print(color2)
输出:
对上面两种颜色执行加操作:
# Add the two colors to create a *new* color object
new_color = color1 + color2
print(new_color)
输出:
Python 对象编程相关推荐
- python对象编程例子-这是我见过最详细的Python面向对象编程!建议收藏!
原标题:这是我见过最详细的Python面向对象编程!建议收藏! 面向对象编程和函数式编程(面向过程编程)都是程序设计的方法,不过稍有区别. 面向过程编程: 1. 导入各种外部库 2. 设计各种全局变量 ...
- python对象编程例子-Python3.5面向对象编程图文与实例详解
本文实例讲述了Python3.5面向对象编程.分享给大家供大家参考,具体如下: 1.面向过程与面向对象的比较 (1)面向过程编程(procedural programming) 面向过程编程又被称为: ...
- python对象编程例子-python编程进阶之类和对象用法实例分析
本文实例讲述了python类和对象用法.分享给大家供大家参考,具体如下: 前面我们都是用python面向过程编程,现在来用python创建类和对象,面向对象编程.类和对象是面向对象编程的两个主要方面. ...
- python对象编程例子-Python 面向对象编程实例讲解
如果你没有任何以往的经验与面向对象(OO)编程,你可能想咨询或至少某种教程的入门课程,所以,你必须掌握的基本概念. 然而,这里是小推出的面向对象编程(OOP)给你带来更好的学习速度: OOP的术语概述 ...
- python对象编程例子-python面向对象编程练习
练习题 1.面向对象三大特性,各有什么用处,说说你的理解. 面向对象的三大特性: 1.继承:解决代码的复用性问题 2.封装:对数据属性严格控制,隔离复杂度 3.多态性:增加程序的灵活性与可扩展性 2. ...
- python对象编程例子-python(十二)面向对象编程、类
面向对象编程 面向对象--Object Oriented Programming,简称oop,是一种程序设计思想.在说面向对象之前,先说一下什么是编程范式,编程范式你按照什么方式来去编程,去实现一个功 ...
- python对象编程例子-python面向对象编程:python类和实例讲解
东尧爱分享 这是东尧每天一篇文章的第51天 东尧写文章的目标:分享东尧的经验和思考,帮你获取物质和精神两方面幸福. 1 什么是对象 在python里面,一切皆为对象.也就是说python里的所有数据都 ...
- python对象编程例子-python 面向对象编程 类和实例
class Student(object): #class后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的.通常,如果没有合适的继承 ...
- python面相对象编程指南_Python面向对象编程指南
抽象是隐藏多余细节的艺术.在面向对象的概念中,抽象的直接表现形式通常为类.虽然Python是解释性语言,但是它是面向对象的,从设计之初就已经是一门面向对象的语言.Python基本上提供了面向对象编程语 ...
最新文章
- C++ Builder初学问与答(十三)
- [SimplePlayer] 4. 从视频文件中提取音频
- python打开文件不存在-Python判断文件是否存在的三种方法
- Windows PE导出表编程2(重组导出表函数地址)
- 面向过程之骑士飞行棋
- 状态输出导航栏html,Vue实现导航栏效果(选中状态刷新不消失)_百厌_前端开发者...
- A10 平板开发一硬件平台搭建
- PAT 1079 Total Sales of Supply Chain[比较]
- BZOJ.4842.[NEERC2016]Delight for a Cat(费用流)
- 集合和Iterator迭代器
- OC Gen X:一键制作黑苹果OpenCore EFI文件
- 维基百科中文语料建模
- 软件-xyplorer
- 网站嵌入YouTube视频
- C#中的Socket
- Rust入门教程(三):Package、Crate 和 Module
- Java实现 蓝桥杯算法提高金明的预算方案
- 量化分析入门5:列表和收盘价的移动平均的示例
- 论文阅读:DEFORMABLE DETR:DEFORMABLE DETR: DEFORMABLE TRANSFORMERSFOR END-TO-END OBJECT DETECTION
- Anaconda打开多个spyder窗口
热门文章
- wordpress主题_27个最适合平面设计师的WordPress主题
- 区块链三加一:错过中国锦鲤,那就来成为区块链锦鲤吧!
- 计算机应用基础指法实训报告,计算机应用基础实训练习册
- jquery插件介绍(六)
- emlog php7,emlog5.3.1兼容PHP7
- 接口测试(二)—— Postman用法详解、newman生成测试报告
- 隔年增长的题_如何从资料分析中的隔年增长率?
- 中望cad文字显示问号怎么办_为什么CAD图纸中用操作系统字体的文字会显示为问号...
- 计算机桌面屏幕设置,双显示器设置:如何设置一台电脑两个显示器
- 一篇文章带你了解折线图