python import custom modules and packages

References

https://blog.csdn.net/gvfdbdf/article/details/52084144

http://www.runoob.com/python/python-modules.html

Basic concepts of python

python module

A Python module (Module) is a Python file that ends with .py and contains Python object definitions and Python statements.

Modules allow you to logically organize your Python code snippets.

Distributing related code into a module makes your code easier to use and easier to understand.

Modules can define functions, classes and variables, and modules can also contain executable code.

python package

A package is a hierarchical file directory structure that defines a Python application environment consisting of modules, subpackages, and subpackages under subpackages.

Simply put, a package is a folder, but there must be an __init__.py file in the folder, and the content of this file can be empty. __init__.py  is used to identify the current folder as a package.

Scenario application

Import sibling directory files

If you need to import files in the same directory, you can use the form of importing a module, which can be called.

Consider two python files in the same directory, test.py needs to call the function in support.py, the directory structure is as follows:

|-- test.py
|-- support.py

The code in support.py is as follows:

def print_func( par ):
   print "Hello : ", par
   return

 

The code called by test.py is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#Import module 
import support
 
#Can now call the functions contained in the module 
support.print_func( " Runoob " )

 

 

import subdirectory files

If you need to import files in a subdirectory, you can use the form of importing a package to encapsulate the subdirectory into a package, which can be called.

Consider a  runoob1.py, runoob2.py, __init__.py  file in the package_runoob  directory  , test.py is the code of the test calling package, and the directory structure is as follows:

test.py
package_runoob
|-- __init__.py
|-- runoob1.py
|-- runoob2.py

__init__.py can be an empty file.

The test.py calling code is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 导入 Phone 包
from package_runoob.runoob1 import runoob1
from package_runoob.runoob2 import runoob2
 
runoob1()
runoob2()

You can also use:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 导入 Phone 包
import package_runoob.runoob1
import package_runoob.runoob2
 
package_runoob.runoob1.runoob1()
package_runoob.runoob2.runoob2()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325028612&siteId=291194637