How do I create a header file in python ?
I know the steps to do it in C++ but I don't know how to do it in python.
-
2Does this answer your question? Does python have header files like C/C++?Max Feinberg– Max Feinberg2019-11-15 06:51:58 +00:00Commented Nov 15, 2019 at 6:51
-
you shouyld look into python and pakagesVaibhav– Vaibhav2019-11-15 06:53:28 +00:00Commented Nov 15, 2019 at 6:53
-
Why do you think you need a header file? If you explain why you're trying to make a header file, we can explain what you actually need to do instead.user2357112– user23571122019-11-15 06:56:06 +00:00Commented Nov 15, 2019 at 6:56
-
See also: docs.python.org/3/tutorial/modules.htmlFObersteiner– FObersteiner2019-11-15 06:59:46 +00:00Commented Nov 15, 2019 at 6:59
4 Answers
You can do something like this:
create a new python file (e.g.:
pseudo_header) here you can add function, variables etc.Example - in
pseudo_header:name = "Bob"in your
main.pydo this:import pseudo_header print(pseudo_header.name) << "Bob" pseudo_header.name = "John" print(pseudo_header.name) << "John"
Comments
Python is not having header files like c++. Instead we import libraries here.
For example take below small piece of code.
import datetime
print datetime.datetime.now()
Output
2019-11-15 12:33:33.177000
Here we are importing library datetime. datetime.datetime.now() will give you the current date. You can also import only a specific object instead of whole module. Like below.
from datetime import datetime
print datetime.now()
3 Comments
There is no need to define anything before code in python as we did in c++.
You just know about the syntax of the python it will be enough for beginner programming.
But if you want to use some extra libraries then you will need some importing.
Example
print("Hello World")
output
>> Hello World
Similarly you can define variables, do some conditional programming or define some loops etc.
Example
a = 5
if a != 5:
print("I am angry")
if a == 5:
print("I am happy")
output
>> I am happy
See there is no need to do any importing.
But if you want to use some libraries like. DateTime
import datetime
print datetime.datetime.now()
This library deals with date and time and anythings belongs to them.
That is python :)
Comments
What I usually do is create a separate library file with all function definitions and import this in the main script.
Let's say my library is called foo.py, which contains
import numpy as np
def side(area):
'''
Function to get length of the side of a square of a given area.
'''
assert (area > 0), 'Invalid input!'
return np.sqrt(area)
Then, in my main script, I just import the library and use the functions.
import numpy as np
from foo import *
area = 100
print (side(area)) # returns 10
May not be the best way but works for me.