前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python:类的定义与使用

Python:类的定义与使用

作者头像
全栈程序员站长
发布2022-09-07 20:03:04
5080
发布2022-09-07 20:03:04
举报

大家好,又见面了,我是你们的朋友全栈君。

类的定义与使用

cball = Projectile(angle, vel, h0)中, cball传入给self

一个炮弹从某个倾角射出计算水平位移和大致飞行时间的程序

代码语言:javascript
复制
# projectile.py
from math import radians, sin , cos

##############类的定义#######
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)
        self.totaltime = 0.0

    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
        self.totaltime = self.totaltime + time

    def getX(self):
        return self.xpos

    def getY(self):
        return self.ypos
#############################

###############函数定义########
def getIputs():
    a = float(input("Enter the lanuch angle (in degrees):"))
    v = float(input("Enter the lanuch velocity (in meters/sec):"))
    h = float(input("Enter the lanuch height (in meters):"))
    t = float(input("Enter the internal between position calculations:"))
    return a, v, h, t

def main():
    angle, vel, h0, time = getIputs()
    cball = Projectile(angle, vel, h0)
    while cball.getY() >= 0:
        cball.update(time)
    print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()))
    print("\nTotal time spent is roughly: {0:0.1f} sceonds.".format(cball.totaltime))
#############################

###########函数调用###########
if __name__ == '__main__':
    main()

运行示例:

代码语言:javascript
复制
'''
Enter the lanuch angle (in degrees):50
Enter the lanuch velocity (in meters/sec):1
Enter the lanuch height (in meters):50
Enter the internal between position calculations:1

Distance traveled: 2.6 meters.

Total time spent is roughly: 4.0 sceonds.

'''

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/156119.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 类的定义与使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档