In this topic Importing variables from one file to another is common in Python. It is used for many reasons, such as to make code modular and reusable, for data sharing, and to organize code into separate files. Now let us give an example which is given below.
Import variables from another file in Python
#hello.py class MyVar: a = "Hello CodeSpeedy" b = 568
In this Python code, we have created a file named hello.py.In this code, I have created the file hello.py . In this code we have created a class named MyVar And two variables have been created, one of which is an integer and the other is a string, whose names are a = “Hello CodeSpeedy” string and another variable is integer b = 568. Now let’s import this file.
from hello import MyVar print(MyVar.a) print(MyVar.b)
In this code, we have imported the class MyVar from the Python file hello.py .
This code is used to import variables a and b from a class MyVar defined in a Python file named hello.py, and then print their values.
1. from hello import MyVar
- This line imports the class MyVar from a Python file named hello.py located in the same directory.
2. print(MyVar.a)
- This line prints the value of the variable a defined as a class variable within the MyVar class.
3. print(MyVar.b)
- This line prints the value of the variable b defined as a class variable within the MyVar class.
Here is the output of this code:
a = "Hello CodeSpeedy" b = 568
This post is about how to import variables from another file into Python.