How does python call a function in another py file

In Python, functions in another .py file can be called by importing modules. Specific steps are as follows:

  1. Create a .py file that contains the functions that need to be called, for example:

  2. In the code file that calls this function, use importkeywords to import this .py file (note, make sure that the two files are in the same directory), for example:

    # file: my_functions.py
    
    def add(a, b):
        return a + b
    
    def subtract(a, b):
        return a - b
    
    # file: main.py
    
    import my_functions
    
    result1 = my_functions.add(3, 4)
    result2 = my_functions.subtract(5, 2)
    
    print(result1, result2)
    

  3. In this example, importthe my_functions.py file is first imported using keywords, and then my_functionsthe functions in it can be called using this namespace. For example, the add() and subtract() functions are called on line 6 and line 7 respectively, and the results are assigned to the result1 and result2 variables.

  4. Finally, the values ​​of result1 and result2 are printed out on line 9.

    After running the main.py file, you will get the output: 7 3.

In addition to the above methods, you can also use the from...import... form to import functions in the module. For example, the main.py code above can be modified to:

 
 

pythonCopy code

# file: main.py

from my_functions import add, subtract

result1 = add(3, 4)
result2 = subtract(5, 2)

print(result1, result2)

In this example, the functions add and subtract to be used are directly imported into the namespace of the current file by using the form of from...import.... This way, their names can be used directly when calling functions.

Guess you like

Origin blog.csdn.net/qq_50942093/article/details/131007872