Detailed explanation of calling of functions classes and variables in different modules of python

  • 2021-07-18 08:34:08
  • OfStack

Firstly, two methods of introducing modules are introduced.

Method 1: Introduce the whole file

import file name

File name. Function name ()/file name. Class name

This method allows you to run functions in another file

Method 2: Introduce only 1 class/function/variable in a file

When you need to import multiple functions or variables from a file, separate them with commas

from file name import function name, class name, variable name

Next, a specific example is given to illustrate the specific method of introducing the module:

Suppose you create a new python package test2 with an python file named run. py and a function named running () in the run. py file. Of course, when creating the test2 package, the system automatically generates a __init__.py file. Now we need to run the running () function in a. py file outside the package. What should we do?

First of all, the first step is to introduce this module in the. py file outside the package. Here are four ways to introduce it.

1. Introduce run module first


from test2 import run

Call the running () function


run.running()

2. Introduce the run function directly from the run module and run it directly


from test2.run import running
running()

3. You need to introduce the running function in the __init__. py file in the test2 package


# From run Introduced into the module running() Function 
#. Imported from the current directory  .. Is a parent directory 
from .run import running

Then directly introduce test2 package, and directly use the package name. Function name, you can use


import test2
test2.running()

4. Same as 3. You first need to introduce the running function in the __init__. py file in the test2 package.


from .run import running

Then directly introduce the running function


from test2 import running
running()

When a very long function is introduced, the introduced function/class/variable can be renamed with as

For example:


from test2 import sleep_time_from_time_or_day as e
e()

Related articles: