我试图写一个程序,它代表了一个简单的类来模拟弹丸的飞行,并返回最大高度和旅行距离。到目前为止,我掌握的情况如下:
th import sin, cos, radians
class Projectile:
"""Simulates the flight of simple projectiles near the eath's surface, ignoring
wind resisitance. Tracking is done in two dimensions, height(y) and distance(x)."""
def __init__(self, angle, velocity, height):
"""Create a projectile with given launch angle, initial velocity and height."""
self.xpos = 0.0
self.ypos = height
theta = radians(angle)
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
#Find time to reach projectiles max height.
self.th = self.yvel/9.8
def update(self, time):
"""Update the stat of this projectile to move in time seconds farther into its flight"""
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.maxpos = max(self.maxypos, self.ypos)
def getY(self):
"""Returns the y position (height) of this projectile."""
return self.ypos
def getX(self):
"""Returns the x position (distance) of this projectile."""
return self.xpos
def getMaxHeight(self):
"""Returns the max height of the projectile."""
return self.maxypos
def getInputs():
a = eval(input("Enter the launch angle (in degrees): "))
v = eval(input("Enter the inital velocity (in meters/sec): "))
h = eval(input("Enter the inital height (in meters): "))
t = eval(input("Enter the time interval between position calculations:"))
return a, v, h, t
def main():
angle, vel, h0, time = getInputs()
elapsedTime = 0.0
cball = Projectile(angle, vel, h0)
cball.getInputs()
while cball.getY() >= 0:
cball.update(time)
elapsedTime + time
print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX()),
" in {0:0.1f} seconds.".format(elapsedTime))
print("\nMaximum height traveled: {0:0.1f} meters.".format(cball.getMaxY()))
if __name__ == "__main__":
main()
但是,main()中缺少了一些东西,因为它一直告诉我“getInputs”没有定义,而且我一辈子都搞不清楚。任何帮助都将不胜感激。你知道吗
在
getInputs
中缺少作为参数的self
。应该是的然后你可以用
cball
来调用它。你知道吗编辑:以上建议将使
cball.getInputs()
起作用。你知道吗但正如注释中提到的,另一种解决方案是将getInputs()从Projective类中移出,在这种情况下,您不会将'self'作为参数传递。你知道吗
更正缩进后,它就可以工作了;此时,getInputs()函数的缩进方式可能会将其定位到类中。
行
cball.getInputs()
是冗余的。eval
对用户原始输入不是一个好主意,可以执行任意代码。你知道吗一般来说,将i/o与业务逻辑结合起来不是一个好主意。您的类不应该包含i/o;将
getInputs()
保留为函数更好。你知道吗相关问题 更多 >
编程相关推荐