Getting started with Python 24 - import, name, main__

In addition to built-in objects, both standard library objects and extension library objects need to be imported with import before use.

1, Import module

(1) Basic statement: import module name [as module alias]

After importing a module, you can use the classes, functions, objects, etc. in the module, but you need to add the prefix "module name" when you use it. In order to simplify the prefix, you can use the "as module alias" method to get an alias for the module when importing. However, after taking the alias, the original name becomes invalid. For example:

import datetime
d = datetime.date.today()
t = datetime.datetime.now()
print(d,t)    # 2020-02-03     2020-02-03 11:35:20.937157

print(dir(datetime))    # View all objects in the module: ['maxhear ',...'tzinfo']
print(dir(datetime.date))    # View all members in the class: ['[add',...'weekday ','year']

import datetime as dt    # Give datetime an alias
d01 = dt.date.today()
t01 = dt.datetime.now()
print(d01,t01)    # 2020-02-03     2020-02-03 11:37:21.739067
d02 = datetime.date.today()    # Invalid original name: NameError: name 'datetime' is not defined

(2) Import multiple modules at the same time: import module 1 [as module 1 alias], module 2 [as module 2 alias]
For example:

import os, sys , datetime as dt, math    # Import os, sys, datetime, math at the same time
print(dt.date.today(), math.ceil(2.98))    # 2020-02-03    3

2, Importing objects in a module

(1) Basic statement: from module name import object name [as object alias]

This method imports not all objects in the whole module, but the specified objects. Objects imported in this way do not need to be prefixed with "module name." when they are used. Of course, this also brings a problem: in the case of importing multiple modules, if there is the phenomenon of duplicate object names, the duplicate objects will shield each other. Objects can also be aliased during import. For example:

from datetime import date    # Import date only

print(date.today())    # 2020-02-03
print(datetime.date.today())    # Do not prefix: NameError: name 'datetime' is not defined
print(datetime.now())    # No import: NameError: name 'datetime' is not defined

(2) Import multiple objects at the same time: from module name import object 1 [as object 1 alias], object 2 [as object 2 alias]

For example:

from datetime import date as dd, datetime as tt
print(dd.today(), tt.now())    # 2020-02-03    2020-02-03 12:57:32.903249

(3) Import all objects in the module: from module name import*

For example:

from datetime import *
print(date.today(), datetime.now())    # 2020-02-03 2020-02-03 12:59:41.594610

3, Import custom module

The statement of importing custom module is the same as that of importing standard library module, but because the standard library module is stored by the system itself and is generally placed in a fixed directory, the path problem is generally not considered when importing, and the custom module is not the same. If the storage directory of the module is not clear, the system will not find the module file, so that the import is lost Defeat.

You cannot specify the directory of the module in the import statement. For example: import C: / mymod, this statement is wrong.

1. Current directory

When importing a module, the system first looks for the module file in the current directory. For example: in the command line window, if the prompt is: D:\py >, first look for the module file in the D:\py directory, and then import the module file as soon as it is found.

2. Directories listed in sys.path

If the system does not find the module file in the current directory, check the directories listed in sys.path, and then search in each directory in the order before and after. If it finds it, import it, and if it cannot find it, throw an exception: ModuleNotFoundError.

(1) See which directories are already in sys.path: print(sys.path).

For example:

import sys
print(sys.path)    # ['D:\\py\\python38.zip', 'D:\\py']

(2) Add a directory at the end of the sys.path directory list: sys.path.append (directory name).

For example:

import sys
sys.path.append('D:\\aa')
sys.path.append('D:\\bb')
sys.path.append('D:\\cc')

print(sys.path)    # ['D:\\py\\python38.zip', 'D:\\py', 'D:\\aa', 'D:\\bb', 'D:\\cc']

(3) Insert the directory before the specified sequence number of the sys.path directory list: sys.path.insert (sequence number, directory name)

For example:

import sys;
sys.path.append('D:\\aa')
sys.path.insert(2,'D:\\dd')
sys.path.insert(0,'D:\\ee')

print(sys.path)    # ['D:\\ee', 'D:\\py\\python38.zip', 'D:\\py', 'D:\\dd', 'D:\\aa']

After setting the directory, you can import the custom module. For example:

Create a file: E:\testpy\py05.py, as follows:

class c01:pass
class c02:pass
def fun01():pass
def fun02():pass

Import the p05 module:

import sys
sys.path.append('E:\\testpy')
import py05
print(dir(py05))
# ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
# '__package__', '__spec__', 'c01', 'c02', 'fun01', 'fun02']

print(sys.path)    # ['D:\\py\\python38.zip', 'D:\\py', 'E:\\testpy']

4, Import custom package

Suppose you have the following custom packages and modules:

pybao(E:/testpy/)
    __init__.py
    baopy01.py
    baopy02.py
    pybao01
        __init__.py
    pybao02
        __init__.py
        baopy03.py
        baopy04.py
        pybao11
            __init__.py
            baopy05.py
        pybao12
            __init__.py
            baopy06.py
            baopy07.py
            baopy08.py
            baopy09.py

in other words:
E:/testpy: pybao package
Pybao package includes: pybao 01 package, pybao 02 package
pybao02 package includes: pybao11 package, pybao12 package

(1) Basic statement: import package name

Like importing custom modules, importing custom packages also has a positioning problem. The system also searches the current directory first. If it can't find it, it will check the directories listed in sys.path. Then, it will search each directory in the order before and after. If it can't find it, it will throw an exception.

The "import package name" statement does not import all the modules and objects in the package. Its only result is to cause the "init. Py" in the package to be executed.

For example, the content of E:/testpy/pybao/init.py is:

print('This is __init__.py of pybao')
import sys
sys.path.append('E:\\testpy')

import pybao    # This is __init__.py of pybao

After "init. Py" is executed, if there are imported statements in this file, the corresponding modules and objects will be imported. For example: e: / testpy / pybao / uinit_u.py:

print('This is __init__.py of pybao')

import sys
sys.path.append('E:\\testpy\\pybao')
import baopy01,baopy02

For modules imported in this way, the prefix "package name" should be added to the reference, for example:

import sys
sys.path.append('E:\\testpy')
import pybao    # This is __init__.py of pybao
print(dir(pybao.baopy01))    # [... 'c11', 'c12', 'fun11', 'fun12']
print(dir(pybao.baopy02))    # [... 'c21', 'c22', 'fun21', 'fun22']

In short, the "import package name" will not directly import any modules and objects, only trigger the "init". Py "file in the package to be executed.

(2) Package in import package: import big package name. Small package name

During the import process, the init.py file in large package and small package will be executed. For example:

E: The content of / testpy / pybao /. Py is:

print('This is __init__.py of pybao')

E: The content of / testpy / pybao02 / uinit_yu.py is:

print('This is __ init__.py of pybao02')

E: The contents of / testpy / pybao12 /? Init? Are:

print('This is __init__.py of pybao12')

Import package: pybao12

import sys
sys.path.append('E:\\testpy')
import pybao.pybao02.pybao12
# Show:
# This is __init__.py of pybao
# This is __init__.py of pybao02
# This is __init__.py of pybao12

(3) Module in the direct import package: import package name. Module name

During the import process, the "init. Py" file in the package will be executed first, and then the package will be imported. For example:

E: The contents of / testpy / pybao / init.py are:

print('This is __init__.py of pybao')

Import the baopy01.py module in the pybao package:

import sys
sys.path.append('E:\\testpy')

import pybao.baopy01    # This is __init__.py of pybao
print(dir(pybao.baopy01))    # [... 'c11', 'c12', 'fun11', 'fun12']

For modules imported in this way, the prefix "package name" should also be added when referencing, for example:

(4) Directly import multiple modules in the package: from package name import*

This statement does not directly import all modules in the package, but the modules specified by the "all" variable in the "init. Py" file. For example:

E: The contents of / testpy / pybao / pybao02 / pybao12 / init.py are:

print('This is __init__.py of pybao12')
__all__=[baopy05,baopy06]

Module to import pybao12:

import sys
sys.path.append('E:\\testpy')

from pybao.pybao02.pybao12 import *
# Show:
# This is __init__.py of pybao
# This is __init__.py of pybao02
# This is __init__.py of pybao12

print(dir(baopy05))    # [...  'c51', 'c52', 'fun51', 'fun52']
print(dir(baopy06))    # [...  'c61', 'c62', 'fun61', 'fun62']
print(dir(baopy08))    # [...  'c81', 'c82', 'fun81', 'fun82']
print(dir(baopy09))    # NameError: name 'baopy09' is not defined

Modules imported in this way do not need the prefix "package name." when they are referenced.

5, name and main__

After the module is imported, the system will convert it to "module object", and add some data members for the module object by default. For example:
E: The contents of / testpy / py06.py are:

class c06:pass
import sys
sys.path.append('E:\\testpy')
import py06
print(dir(py06))
# Show:
# ['__builtins__', '__cached__', '__doc__', '__file__',
# '__loader__', '__name__', '__package__', '__spec__', 'c06']

A data member named "name" is commonly used in module objects. When the module is directly executed, the system sets the value of "module object" to "main". When the module is imported and then directly executed, the value of "module name" is set to "module name". For example:
E: The contents of / testpy / py06.py are:

class c06:pass;  print('py06 __name__:',__name__)
import sys
sys.path.append('E:\\testpy')

import py06    # py06 __name__: py06

print('my __name__:',__name__)    # my __name__: __main__

In actual programming, it is often used to judge whether a module is being imported by the value of name, so as to avoid some statements being executed during import. For example:

if __name__ == '__main__':    # When the current module is imported, the following statements will not be executed
    x = 100
    y = 200
    z = 300
Published 25 original articles, praised 0, visited 9 / 11
Private letter follow

Keywords: Programming

Added by jwadenpfuhl on Mon, 03 Feb 2020 18:47:58 +0200