實用:python中的模塊導入

from os.path import exists
print(exists)
print(dir())

print('============================================')
from os.path import exists as e
print(e)
print(dir())

print('============================================')
import os
print(os.path.exists)
print(os.path.__dict__['exists'])
print(dir())

運行結果:

<function exists at 0x7f77489c28c8>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'exists']
============================================
<function exists at 0x7f77489c28c8>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'e', 'exists']
============================================
<function exists at 0x7f77489c28c8>
<function exists at 0x7f77489c28c8>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'e', 'exists', 'os']

模塊的查找路徑順序

import sys
for i in sys.path:
    print(i)

運行結果:

/home/yzx/PycharmProjects/python
/home/yzx/PycharmProjects/python
/usr/lib/python35.zip
/usr/lib/python3.5
/usr/lib/python3.5/plat-x86_64-linux-gnu
/usr/lib/python3.5/lib-dynload
/home/yzx/PycharmProjects/python/venv/lib/python3.5/site-packages
/home/yzx/PycharmProjects/python/venv/lib/python3.5/site-packages/setuptools-40.8.0-py3.5.egg
/home/yzx/PycharmProjects/python/venv/lib/python3.5/site-packages/pip-19.0.3-py3.5.egg

查看初始化後模塊的加載詳情:

import sys
for i in sys.modules.items():
    print(i)

執行結果:

('abc', <module 'abc' from '/usr/lib/python3.5/abc.py'>)
('_weakref', <module '_weakref' (built-in)>)
('_bootlocale', <module '_bootlocale' from '/usr/lib/python3.5/_bootlocale.py'>)
('stat', <module 'stat' from '/usr/lib/python3.5/stat.py'>)
('_stat', <module '_stat' (built-in)>)
('marshal', <module 'marshal' (built-in)>)
('errno', <module 'errno' (built-in)>)
('encodings.cp437', <module 'encodings.cp437' from '/usr/lib/python3.5/encodings/cp437.py'>)
('encodings', <module 'encodings' from '/usr/lib/python3.5/encodings/__init__.py'>)
('site', <module 'site' from '/usr/lib/python3.5/site.py'>)
('encodings.utf_8', <module 'encodings.utf_8' from '/usr/lib/python3.5/encodings/utf_8.py'>)
('sys', <module 'sys' (built-in)>)
('os.path', <module 'posixpath' from '/usr/lib/python3.5/posixpath.py'>)
('posix', <module 'posix' (built-in)>)
('_collections_abc', <module '_collections_abc' from '/usr/lib/python3.5/_collections_abc.py'>)
('_sre', <module '_sre' (built-in)>)
('_imp', <module '_imp' (built-in)>)
('_frozen_importlib', <module '_frozen_importlib' (frozen)>)
('sitecustomize', <module 'sitecustomize' from '/usr/lib/python3.5/sitecustomize.py'>)
('sre_constants', <module 'sre_constants' from '/usr/lib/python3.5/sre_constants.py'>)
('_sitebuiltins', <module '_sitebuiltins' from '/usr/lib/python3.5/_sitebuiltins.py'>)
('_sysconfigdata', <module '_sysconfigdata' from '/usr/lib/python3.5/_sysconfigdata.py'>)
('_signal', <module '_signal' (built-in)>)
('_thread', <module '_thread' (built-in)>)
('encodings.aliases', <module 'encodings.aliases' from '/usr/lib/python3.5/encodings/aliases.py'>)
('_codecs', <module '_codecs' (built-in)>)
('os', <module 'os' from '/usr/lib/python3.5/os.py'>)
('_weakrefset', <module '_weakrefset' from '/usr/lib/python3.5/_weakrefset.py'>)
('re', <module 're' from '/usr/lib/python3.5/re.py'>)
('_warnings', <module '_warnings' (built-in)>)
('zipimport', <module 'zipimport' (built-in)>)
('encodings.latin_1', <module 'encodings.latin_1' from '/usr/lib/python3.5/encodings/latin_1.py'>)
('_io', <module 'io' (built-in)>)
('posixpath', <module 'posixpath' from '/usr/lib/python3.5/posixpath.py'>)
('__main__', <module '__main__' from '/home/yzx/PycharmProjects/python/t34.py'>)
('sre_compile', <module 'sre_compile' from '/usr/lib/python3.5/sre_compile.py'>)
('genericpath', <module 'genericpath' from '/usr/lib/python3.5/genericpath.py'>)
('sre_parse', <module 'sre_parse' from '/usr/lib/python3.5/sre_parse.py'>)
('io', <module 'io' from '/usr/lib/python3.5/io.py'>)
('sysconfig', <module 'sysconfig' from '/usr/lib/python3.5/sysconfig.py'>)
('codecs', <module 'codecs' from '/usr/lib/python3.5/codecs.py'>)
('copyreg', <module 'copyreg' from '/usr/lib/python3.5/copyreg.py'>)
('_frozen_importlib_external', <module '_frozen_importlib_external' (frozen)>)
('_locale', <module '_locale' (built-in)>)
('_sysconfigdata_m', <module '_sysconfigdata_m' from '/usr/lib/python3.5/plat-x86_64-linux-gnu/_sysconfigdata_m.py'>)
('builtins', <module 'builtins' (built-in)>)

主模塊:

import sys
print(__name__)
print(sys.modules['__main__'])

運行結果:

__main__
<module '__main__' from '/home/yzx/PycharmProjects/python/t34.py'>

模塊名的應用:(name__和__main)
子模塊文件:t33

class A:
    def show(self):
        print('hello the world')

if __name__ == '__main__':
    print('test')
    a = A()
    a.show()
    print('test seccess')
else:
    print('work start')

運行結果:(相當於測試)

test
hello the world
test seccess

主模塊文件:t34

import t33 # 導入t33子模塊
if __name__ == '__main__':
    a = t33.A()
    a.show()
else:
    print('error')

運行結果:(運行主模塊)

work start
hello the world

子模塊導入
模塊結構:
在這裏插入圖片描述
init文件格式:
在這裏插入圖片描述
子模塊格式:
在這裏插入圖片描述
代碼如下:

import m
print(m)
print(m.__file__)
print(m.A.__module__)
print(m.__cached__)
print(m.__path__)
print(m.__package__)
print(dir(m))
print('==========================================================')

from m.m1.m11 import C
print(dir())
print('==========================================================')

from m.m1 import B # 重複導入不執行__init__.py代碼
print(dir())

運行結果:

m
<module 'm' from '/home/yzx/PycharmProjects/python/m/__init__.py'>
/home/yzx/PycharmProjects/python/m/__init__.py
m
/home/yzx/PycharmProjects/python/m/__pycache__/__init__.cpython-35.pyc
['/home/yzx/PycharmProjects/python/m']
m
['A', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'm_init']
==========================================================
m.m1
m.m1.m11
['C', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'm']
==========================================================
['B', 'C', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'm']

模塊的層級關係:
使用" . .. ..."分別代表查找當前目錄,上一層目錄,上上層目錄
使用"m m1 m11"分別代表嵌套中的頂層目錄,第二層目錄,第三層目錄
使用"x y z"分別代表頂層目錄文件,第二層目錄文件,第三層目錄文件,如下圖:
在這裏插入圖片描述
我們使用第三層目錄文件z,去導入頂層的x文件,z文件代碼如下:

#print(__name__) 註釋
#m11_arg = 'world' 註釋

from ... import x as firstx  # 此處雖然可以導入,但卻不可以直接運行,因爲直接運行會被當做主模塊運行,但主模塊作爲頂層模塊是不允許使用相對路徑運行,應該使用絕對路徑

print(firstx.m_arg)

運行結果:

Traceback (most recent call last):
__main__
  File "/home/yzx/PycharmProjects/python/m/m1/m11/z.py", line 4, in <module>
    from ... import x as firstx  # 不可以作爲主模塊運行
SystemError: Parent module '' not loaded, cannot perform relative import

但是如果是其他模塊調用則可以正常被查找到
此處我們新建一個新模塊去調用z中的firstx看能不能成功打印
在這裏插入圖片描述
新模塊代碼如下:

import  m.m1.m11.z
print('t35 = ',m.m1.m11.z.firstx.m_arg)

運行結果:

m
m.m1
m.m1.m11
m.m1.m11.z
m.x
hello #成功執行了z模塊代碼
t35 =  hello  #剛剛在z模塊直接運行取不到的值,現在在新模塊中可以取到

模塊中的訪問控制
在這裏插入圖片描述
在初始化m模塊提供保護變量和私有變量

print(__name__)
class A:
    pass
m_init = 'hello the world'

_x = '_x'
__y = '__y'

在調用m模塊時候,第一種方法:
在這裏插入圖片描述
指明要導入的變量(屬性名),則可以正常訪問

from m import _x,__y

print(dir())

print(_x)
print(__y)

運行結果:

m
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__y', '_x']
_x
__y

不指明的要導入的變量,而使用*看似導入所有,但是並不導入私有的和保護的屬性
在這裏插入圖片描述

from m import *

print(dir())

print(_x)
print(__y)

運行結果:(拋異常,取不到屬性的值了)

Traceback (most recent call last):
  File "/home/yzx/PycharmProjects/python/t35.py", line 5, in <module>
    print(_x)
NameError: name '_x' is not defined
m
['A', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'm_init']

上面解決方法:
在這裏插入圖片描述

print(__name__)
class A:
    pass
m_init = 'hello the world'

_x = '_x'
__y = '__y'

__all__ = ['m_init','_x','__y']

在這裏插入圖片描述

from m import *

print(dir())

print(_x)
print(__y)

運行結果:(可以使用*導入保護變量和私有變量了)

m
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__y', '_x', 'm_init']
_x
__y

變量的收集

from m import *

print(dir()) #dir只收集局部作用域中,在它代碼之上的變量(包括模塊導入的屬性),m=5代碼在dir之後所以dir不收集m

m = 5

def foo(y):
    x = 6
    print(dir())  #dir只收集局部作用域中,在它代碼之上的變量(包括模塊導入的屬性),z=5代碼在dir之後所以dir不收集m
    print(sorted(locals().keys())) #locals和dir是一樣的

    z = 5
foo(7)

運行結果:

m
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__y', '_x', 'm_init']
['x', 'y']
['x', 'y']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章