Summary of import methods of python package

  • 2021-09-12 01:38:14
  • OfStack

1. from... import import

from package import module1, module2, module3, ... ...

This import method does not execute the contents of __init__.


from pkg01 import p01
p01.sayHello()

2. from package import *

Import all functions and classes in the current package __init__. py file.

Usage


func_name()
class_name.func_name()
class_name.var

3. import package. module

Import a specific module in the package.

Usage


package.module.func_name
package.module.class.fun()
package.module.class.var

Extension of knowledge points:

How to import modules

The module is an Python file of type. py You don't need the. py suffix when importing, just import the file name directly Direct import using import: Syntax: import module_name Usage: module_name.class_name or module.func_name Import module with import and set 1 alias Syntax: import module_name as XXX Usage: XXX.class_name or XXX.funct_name With the help of from copying module properties, you can import only some classes or functions or variables in the module Syntax: from module_name import class_name, funct_name How to use it: directly call a function or instantiate a class Note, however, that when from imports variables from a module, it will cause variables with the same name to be overwritten, which means that namespaces of different modules will overlap here. Import the full contents of the module with from... import * Syntax: from module_name import * When you use it, you can call the function or instantiate the class directly Using importlib module to import modules beginning with numbers Syntax: import importlib XXX = importlib.import_module("module_name") XXX.class_name or XXX.func_name when used

How to import packages

A package is a folder that contains many modules You can also have sub-packages within the package Import packages directly using import (only import the contents in __init__. py) Syntax: import package_name Import 1 package directly, and only use all the contents in _init_. py Use: package_name.func_name or package_name. class Import a 1 module in the package Syntax: import package_name.module_name Use: package_name.module_na112afme.func_name or package_name.module_name.class_name

Related articles: