Reputation: 9
I am a novice Python programmer and I am practicing imports but I have a problem because I don't know how to import a program from a module, thanks in advance for your help. I have tried many solutions but always some error appears.... Folder (modul) --> missile.py --> Code of Class 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()
and
def __init__(self, Firing_angle=20, Initial_velocity=120):
result:
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..
I'm out of ideas on how to do this, thank you in advance for your help :D
Upvotes: 1
Views: 44
Reputation: 54698
There are a couple of things here. Your first example is almost right. However, your call_block
needs to use the self
it is given, not the global 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
The bigger thing is that all the code you have inside if __name__ == '__main__':
actually needs to be in the main file. That code will never run when the file is imported. So, remove that code from the module, and make your 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]}...)
Upvotes: 1