Python import from class



我是一个新手Python程序员,我正在练习导入,但我有一个问题,因为我不知道如何从模块导入程序,提前感谢您的帮助。我已经尝试了许多解决方案,但总是出现一些错误....文件夹(模块)——>missile.py——比;船级代码main.py

missile.py:

import math
import matplotlib.pyplot as plt
G = 9.81
class Missile():
def __init__(self, Firing_angle, Initial_velocity):
...
def equation_of_trajectory(self):
...
def flight_path_envelope_for_constant_speed(self):
...
def axis_of_symmetry(self):
...
def velocity_of_flight(self):
...
def elements_of_path(self):
...
def call_block(self):
a = Pr.equation_of_trajectory()
b = Pr.flight_path_envelope_for_constant_speed()
c = Pr.axis_of_symmetry()
d = Pr.velocity_of_flight()
e = Pr.elements_of_path()
plt.plot(a)
plt.plot(b)
plt.plot( )
plt.plot(d)
plt.show( )
return e
def __str__(self):
...

if __name__ == '__main__':
while True:
try:
Pr = Missile(float(input('Firing_angle       [o]:      ')),
float(input('Initial_velocity [m/s]:      ')))
break
except ValueError:
print('Wrong Value!')
resume = Pr.call_block()
print(f'Projectile launch point [m]: {resume[0]}...)

main.py:ver.1

from Modul.missile import Missile
if __name__ == '__main__':
Missile()
TypeError: __init__() missing 2 required positional arguments: 'Firing_angle' and 'Initial_velocity'
--------------------------------------------------------------------------------

ver.2

from Modul.missile import Missile
if __name__ == '__main__':
Missile()

def __init__(self, Firing_angle=20, Initial_velocity=120):

结果:

Process finished with exit code 0
--------------------------------------------------------------------------------

ver.3

from Modul.missile import Missile
if __name__ == '__main__':
Firing_angle, Initial_velocity = Missile.call_block()
TypeError: call_block() missing 1 required positional argument: 'self'... etc..

我不知道该怎么做,提前感谢您的帮助:D

这里有几件事。你的第一个例子几乎是正确的。但是,您的call_block需要使用给定的self,而不是全局Pr:

def call_block(self):
a = self.equation_of_trajectory()
b = self.flight_path_envelope_for_constant_speed()
c = self.axis_of_symmetry()
d = self.velocity_of_flight()
e = self.elements_of_path()
plt.plot(a)
plt.plot(b)
plt.plot(c)
plt.plot(d)
plt.show()
return e

更重要的是,if __name__ == '__main__':内部的所有代码实际上都需要在主文件中。当导入文件时,该代码将永远不会运行。因此,从模块中删除该代码,并将main.py:

from Modul.missile import Missile
if __name__ == '__main__':
while True:
try:
Pr = Missile(
float(input('Firing_angle       [o]:      ')),
float(input('Initial_velocity [m/s]:      ')))
break
except ValueError:
print('Wrong Value!')
resume = Pr.call_block()
print(f'Projectile launch point [m]: {resume[0]}...)

相关内容

最新更新