Python import 与 __all__

import module

使用from <module> import *导入模块时,若显式定义了__all__,则只导入__all__中的name,否则会导入除以下划线开头的所有name

文件目录结构

|---main.py
|---module.py

定义module文件:

# __all__ in a module, means that when you import * from the module, only those names in the __all__ will imported
__all__ = ['hello', 'Person', '__private']
​
_internal = 'internal'__private = 'private'
​
​
class Person():
    def __init__(self):
        print('init person')
​
​
def hello():
    print('hello')
​
​
def world():
    print('world')

 

导入模块:

import module
​
module.Person()
module.hello()
# 可以访问以下划线开头的name
print(module._internal)
module.world()
​
# ======================================
from module import *
​
Person()
hello()
print(__private)
​
# NameError: name 'world' is not defined
# world()
# NameError: name '_internal' is not defined
print(_internal)

 

import package

package中的__init__.py文件会影响到包文件的导入

文件目录结构

|---main.py
|---packages
|---__init__.py
|---pkg.py

__init__.py为空,main.py

import packages.pkg as ppkg
​
ppkg.Package()
ppkg._internal
​
# =============================================
from packages import pkg
​
pkg.Package()
​
# =============================================
# 不会导入任何name
from packages import *

 

__init__.py中指定模块name

__init__.py

__all__ = ['pkg']

main.py

import packages.pkg as ppkg
​
ppkg.Package()
ppkg._internal
​
# =============================================
from packages import *
​
pkg.Package()
pkg._internal

__init__.py中导出模块中的部分名称

__init__.py

from pkg import *__all__ = ['Package', 'init']

main.py

import packages as pg
​
pg.Package()
​
# ============================================
from packages import Package
​
Package()
​
# =============================================
from packages import pkg
​
# AttributeError: 'function' object has no attribute 'Package'
# pkg.Package()
# =============================================
from packages import *
​
Package()
init()
# name 'pkg' is not defined
# pkg.Package()
# pkg._internal

 

对于package的导入,若__init__.py不为空,则只能导入__init__.py中指定的模块(中的)name;

__init__.py为空时,通过from package import *无法导入任何name;

 

推荐阅读

Python Modules

Python Package

Python Namespace and Scope

Can someone explain all in Python?

posted @ 2020-06-15 11:56  雪飞鸿  阅读(537)  评论(0编辑  收藏  举报