python通过面向对象程序设计方法 实现铅球运行轨迹的计算
2016-04-29 10:53
846 查看
本文我们通过面向对象程序设计的方法,实现铅球运行轨迹计算的程序。
这个问题中有一个铅球对象,它有4个属性:xpos,ypos,xvel,yvel
构建投射体的类Projectile用来生成铅球对象,不断的更新对象变量,以此来描述这个问题。
用python3编写Projectile.py文件和main_qianqiu.py文件。
Projectile.py文件如下:
from math import sin,cos,radians
class Projectile:
def __init__(self,angle,velocity,height):
#根据给定的发射角度,初始速度和位置创建一个投射体对象
self.xpos=0.0
self.ypos=height
theta=radians(angle)
self.xvel=velocity*cos(theta)
self.yvel=velocity*sin(theta)
def update(self,time):
#更新投射体的状态
self.xpos=self.xpos+time*self.xvel
yvel1=self.yvel-9.8*time
self.ypos=self.ypos+time*(self.yvel+yvel1)/2.0
self.yvel=yvel1
def getY(self):
#返回投射体的y轴坐标
return self.ypos
def getX(self):
#返回投射体的x轴坐标(即水平距离)
return self.xpos
找到python的安装目录,将Projectile.py文件放到文件夹python35/Lib中,如下图:
main_qianqiu.py文件内容如下:
from Projectile import *
def getInputs():
a=eval(input('Enter the launch angle(in degrees):'))
v=eval(input('Enter the initial velocity(in meters/sec):'))
h=eval(input('Enter the initial height(in meters):'))
t=eval(input('Enter the time interval:'))
return a,v,h,t
def main():
angle,vel,h0,time=getInputs()
shot=Projectile(angle,vel,h0)
while shot.getY()>=0:
shot.update(time)
print('\nDistance traveled:{0:0.1f} meters.'.format(shot.getX()))
if __name__=='__main__':
main()
运行main_qianqiu.py文件,输入输出如下:
(完)
这个问题中有一个铅球对象,它有4个属性:xpos,ypos,xvel,yvel
构建投射体的类Projectile用来生成铅球对象,不断的更新对象变量,以此来描述这个问题。
用python3编写Projectile.py文件和main_qianqiu.py文件。
Projectile.py文件如下:
from math import sin,cos,radians
class Projectile:
def __init__(self,angle,velocity,height):
#根据给定的发射角度,初始速度和位置创建一个投射体对象
self.xpos=0.0
self.ypos=height
theta=radians(angle)
self.xvel=velocity*cos(theta)
self.yvel=velocity*sin(theta)
def update(self,time):
#更新投射体的状态
self.xpos=self.xpos+time*self.xvel
yvel1=self.yvel-9.8*time
self.ypos=self.ypos+time*(self.yvel+yvel1)/2.0
self.yvel=yvel1
def getY(self):
#返回投射体的y轴坐标
return self.ypos
def getX(self):
#返回投射体的x轴坐标(即水平距离)
return self.xpos
找到python的安装目录,将Projectile.py文件放到文件夹python35/Lib中,如下图:
main_qianqiu.py文件内容如下:
from Projectile import *
def getInputs():
a=eval(input('Enter the launch angle(in degrees):'))
v=eval(input('Enter the initial velocity(in meters/sec):'))
h=eval(input('Enter the initial height(in meters):'))
t=eval(input('Enter the time interval:'))
return a,v,h,t
def main():
angle,vel,h0,time=getInputs()
shot=Projectile(angle,vel,h0)
while shot.getY()>=0:
shot.update(time)
print('\nDistance traveled:{0:0.1f} meters.'.format(shot.getX()))
if __name__=='__main__':
main()
运行main_qianqiu.py文件,输入输出如下:
(完)
相关文章推荐
- Windows系统本地安装Python常用库
- python第一站
- ubuntu 配置python环境
- [python]初探socket
- python第一讲练习题
- [Python笔记]第一篇:基础知识
- Python:字符串处理
- python 递归
- Python+Opencv进行识别相似图片
- Python之 list 用法二
- python遍历删除字典里值为空的元素报错
- Python过滤列表用法实例分析
- Python学习笔记《Head first for Python》
- Python 安装环境
- Python松散正则表达式用法分析
- 机器学习----使用python仿写theano中RBM的源代码
- python中私有函数调用方法解密
- Python3爬虫百度图片搜索的图片
- 简单学习Python time模块
- python字符串相关操作