• Python包模块化调用方式详解


            Python包模块化调用方式详解

                               作者:尹正杰

    版权声明:原创作品,谢绝转载!否则将追究法律责任。

     

      一般来说,编程语言中,库、包、模块是同一种概念,是代码组织方式。 Python中只有一种模块对象类型,但是为了模块化组织模块的便利,提供了"包"的概念。

      模块module,指的是Python的源代码文件。 包package,指的是模块组织在一起的和包名同名的目录及其相关文件。 

    一.导入语句

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 import os
     7 import pathlib  as p1      #倒入模块使用别名
     8 from os.path import exists          #加载、初始化os、os.path模块,exists加入本地名词空间并绑定
     9 
    10 """
    11 总结
    12     找到from子句中指定的模块,加载并初始化它(注意不是导入)
    13  
    14     对于import子句后的名称
    15         1>.先查from子句导入的模块是否具有该名称的属性
    16         2>.如果不是,则尝试导入该名称的子模块
    17         3>.还没有找到,则抛出ImportError异常
    18         4>.这个名称保存到本地名词空间中,如果有as子句,则使用as子句后的名称
    19 """
    20 
    21 if exists('o:/t'):
    22     print('Found')
    23 else:
    24     print('Not Found')
    25 print(dir())
    26 print(exists)
    27 
    28 # 4种方式获得同一个对象exist
    29 print(os.path.exists)
    30 print(exists)
    31 print(os.path.__dict__['exists']) # 字符串
    32 print(getattr(os.path, 'exists')) # 字符串
    33 
    34 
    35 print(p1)
    36 print(p1.Path,id(p1.Path))
    37 print(dir())
    Not Found
    ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'exists', 'os', 'p1']
    <function exists at 0x1006f9d08>
    <function exists at 0x1006f9d08>
    <function exists at 0x1006f9d08>
    <function exists at 0x1006f9d08>
    <function exists at 0x1006f9d08>
    <module 'pathlib' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pathlib.py'>
    <class 'pathlib.Path'> 4328656856
    ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'exists', 'os', 'p1']
    以上代码执行结果戳这里

    二.自定义模块

    1>.自定义模块命名规范

      (1)模块名就是文件名,"*.py"文件就是一个模块
      (2)模块名必须符合标识符的要求,是非数字开头的字母、数字和下划线的组合。test-module.py这样的文件名不能作为模块名。也不要使用中文。
      (3)不要使用系统模块名来避免冲突,除非你明确知道这个模块名的用途 
      (4)通常模块名为全小写,下划线来分割

    2>.案例演示

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 class Point:
     7     def __init__(self,x,y):
     8         self.x = x
     9         self.y = y
    10 
    11     def showModule(self):
    12         print(1,self.__module__,self)
    13         print(2,self.__dict__)
    14         print(3,self.__class__.__dict__)
    15         print(4,self.__class__.__name__)
    16 
    17 
    18     def __repr__(self):
    19         return "Point(x = {},y = {})".format(self.x,self.y)
    20 
    21 p = Point(10,20)
    22 print(p)
    test01.py
    #!/usr/bin/env python
    #_*_conding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie
    
    import test01
    
    a = test01.Point(300,1000)
    a.showModule()
    test02.py
     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 from test01 import Point as p1
     7 
     8 
     9 b = p1(20,30)
    10 b.showModule()
    test03.py

    三.模块搜索顺序

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 import sys
     7 
     8 """
     9 使用 sys.path 查看搜索顺序,路径顺序为
    10     1.程序主目录,程序运行的主程序脚本所在的目录
    11     2.PYTHONPATH目录,环境变量PYTHONPATH设置的目录也是搜索模块的路径 3. 标准库目录,Python自带的库模块所在目录
    12 
    13 温馨提示:
    14     sys.path可以被修改,增加新的目录
    15 """
    16 print(*sys.path,sep="
    ")
    /yinzhengjie/python/devops/python基础/08.模块化
    /yinzhengjie/python/devops
    /Applications/PyCharm.app/Contents/helpers/pycharm_display
    /Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip
    /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7
    /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload
    /yinzhengjie/python/devops/venv/lib/python3.7/site-packages
    /yinzhengjie/python/devops/venv/lib/python3.7/site-packages/setuptools-40.8.0-py3.7.egg
    /yinzhengjie/python/devops/venv/lib/python3.7/site-packages/pip-19.0.3-py3.7.egg
    /Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend
    以上代码输出结果戳这里

    四.模块的重复导入 

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 import sys
     7 print(sys.modules)      #所有加载的模块都会记录在"sys.modules"中,sys.modules是存储已经加载过的所有模块的字典。
     8 
     9 import test01           #第一次加载"test01"模块
    10 
    11 print("local module")
    12 print(sys.modules)      #打印"sys.modules"可以看到os,os.path都已经加载了。
    13 
    14 import test01
    15 import  test01           #我们多次对"test01"模块进行倒入,然而并不会产生重复倒入对现象。
    16 
    17 print(sys.modules)      
    {'sys': <module 'sys' (built-in)>, 'builtins': <module 'builtins' (built-in)>, '_frozen_importlib': <module '_frozen_importlib' (frozen)>, '_imp': <module '_imp' (built-in)>, '_thread': <module '_thread' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_weakref': <module '_weakref' (built-in)>, '_frozen_importlib_external': <module '_frozen_importlib_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'posix': <module 'posix' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>, 'encodings': <module 'encodings' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/__init__.py'>, 'codecs': <module 'codecs' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py'>, '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/aliases.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/utf_8.py'>, '_signal': <module '_signal' (built-in)>, '__main__': <module '__main__' from '/yinzhengjie/python/devops/python基础/08.模块化/test02.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/latin_1.py'>, 'io': <module 'io' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/io.py'>, 'abc': <module 'abc' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/abc.py'>, '_weakrefset': <module '_weakrefset' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_weakrefset.py'>, 'site': <module 'site' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site.py'>, 'os': <module 'os' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py'>, 'errno': <module 'errno' (built-in)>, 'stat': <module 'stat' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/stat.py'>, '_stat': <module '_stat' (built-in)>, 'posixpath': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/posixpath.py'>, 'genericpath': <module 'genericpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/genericpath.py'>, 'os.path': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/posixpath.py'>, '_collections_abc': <module '_collections_abc' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_collections_abc.py'>, '_sitebuiltins': <module '_sitebuiltins' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_sitebuiltins.py'>, '_bootlocale': <module '_bootlocale' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_bootlocale.py'>, '_locale': <module '_locale' (built-in)>, 'encodings.cp437': <module 'encodings.cp437' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/cp437.py'>, 'sitecustomize': <module 'sitecustomize' from '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/sitecustomize.py'>}
    Point(x = 10,y = 20)
    local module
    {'sys': <module 'sys' (built-in)>, 'builtins': <module 'builtins' (built-in)>, '_frozen_importlib': <module '_frozen_importlib' (frozen)>, '_imp': <module '_imp' (built-in)>, '_thread': <module '_thread' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_weakref': <module '_weakref' (built-in)>, '_frozen_importlib_external': <module '_frozen_importlib_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'posix': <module 'posix' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>, 'encodings': <module 'encodings' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/__init__.py'>, 'codecs': <module 'codecs' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py'>, '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/aliases.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/utf_8.py'>, '_signal': <module '_signal' (built-in)>, '__main__': <module '__main__' from '/yinzhengjie/python/devops/python基础/08.模块化/test02.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/latin_1.py'>, 'io': <module 'io' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/io.py'>, 'abc': <module 'abc' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/abc.py'>, '_weakrefset': <module '_weakrefset' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_weakrefset.py'>, 'site': <module 'site' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site.py'>, 'os': <module 'os' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py'>, 'errno': <module 'errno' (built-in)>, 'stat': <module 'stat' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/stat.py'>, '_stat': <module '_stat' (built-in)>, 'posixpath': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/posixpath.py'>, 'genericpath': <module 'genericpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/genericpath.py'>, 'os.path': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/posixpath.py'>, '_collections_abc': <module '_collections_abc' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_collections_abc.py'>, '_sitebuiltins': <module '_sitebuiltins' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_sitebuiltins.py'>, '_bootlocale': <module '_bootlocale' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_bootlocale.py'>, '_locale': <module '_locale' (built-in)>, 'encodings.cp437': <module 'encodings.cp437' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/cp437.py'>, 'sitecustomize': <module 'sitecustomize' from '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/sitecustomize.py'>, 'test01': <module 'test01' from '/yinzhengjie/python/devops/python基础/08.模块化/test01.py'>}
    {'sys': <module 'sys' (built-in)>, 'builtins': <module 'builtins' (built-in)>, '_frozen_importlib': <module '_frozen_importlib' (frozen)>, '_imp': <module '_imp' (built-in)>, '_thread': <module '_thread' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_weakref': <module '_weakref' (built-in)>, '_frozen_importlib_external': <module '_frozen_importlib_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'posix': <module 'posix' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>, 'encodings': <module 'encodings' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/__init__.py'>, 'codecs': <module 'codecs' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py'>, '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/aliases.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/utf_8.py'>, '_signal': <module '_signal' (built-in)>, '__main__': <module '__main__' from '/yinzhengjie/python/devops/python基础/08.模块化/test02.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/latin_1.py'>, 'io': <module 'io' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/io.py'>, 'abc': <module 'abc' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/abc.py'>, '_weakrefset': <module '_weakrefset' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_weakrefset.py'>, 'site': <module 'site' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site.py'>, 'os': <module 'os' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py'>, 'errno': <module 'errno' (built-in)>, 'stat': <module 'stat' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/stat.py'>, '_stat': <module '_stat' (built-in)>, 'posixpath': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/posixpath.py'>, 'genericpath': <module 'genericpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/genericpath.py'>, 'os.path': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/posixpath.py'>, '_collections_abc': <module '_collections_abc' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_collections_abc.py'>, '_sitebuiltins': <module '_sitebuiltins' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_sitebuiltins.py'>, '_bootlocale': <module '_bootlocale' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_bootlocale.py'>, '_locale': <module '_locale' (built-in)>, 'encodings.cp437': <module 'encodings.cp437' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/encodings/cp437.py'>, 'sitecustomize': <module 'sitecustomize' from '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/sitecustomize.py'>, 'test01': <module 'test01' from '/yinzhengjie/python/devops/python基础/08.模块化/test01.py'>}
    以上代码执行结果戳这里

    五.模块运行

    1>.if __name__ == '__main__' 的用途

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 class Point:
     7     def __init__(self,x,y):
     8         self.x = x
     9         self.y = y
    10 
    11     def showModule(self):
    12         print(1,self.__module__,self)
    13         print(2,self.__dict__)
    14         print(3,self.__class__.__dict__)
    15         print(4,self.__class__.__name__)
    16 
    17 
    18     def __repr__(self):
    19         return "Point(x = {},y = {})".format(self.x,self.y)
    20 
    21 p = Point(10,20)
    22 print(p)
    test01.py文件内容
    #!/usr/bin/env python
    #_*_conding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie
    
    import test01
    
    
    """
    if __name__ == '__main__': 用途
        1.本模块的功能测试 对于非主模块,测试本模块内的函数、类
        2.避免主模块变更的副作用 顶层代码,没有封装,主模块使用时没有问题。但是,一旦有了新的主模块,老的主模块成了被导入模块, 由于原来代码没有封装,一并执行了。
    """
    if __name__ == '__main__':
        print("in __main__")
    else:
        print("in imported module")
    Point(x = 10,y = 20)
    in __main__
    以上代码输出结果戳这里

    2>.模块的属性

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 import test01 as  t1
     7 
     8 """
     9 模块的属性如下:
    10     __file__
    11         字符串,源文件路径
    12     __cached__
    13         字符串,编译后的字节码文件路径
    14     __spec__
    15         显示模块的规范
    16     __name__
    17         模块名
    18     __package__
    19         当模块是包,同 __name__ ;否则,可以设置为顶级模块的空字符串
    20 """
    21 
    22 for k,v in t1.__dict__.items():
    23     print(k,str(v)[:80])
    24 
    25 print(dir(t1))
    26 
    27 for name in dir(t1):
    28     print(getattr(t1,name))
    Point(x = 10,y = 20)
    __name__ test01
    __doc__ None
    __package__ 
    __loader__ <_frozen_importlib_external.SourceFileLoader object at 0x1021610b8>
    __spec__ ModuleSpec(name='test01', loader=<_frozen_importlib_external.SourceFileLoader ob
    __file__ /yinzhengjie/python/devops/python基础/08.模块化/test01.py
    __cached__ /yinzhengjie/python/devops/python基础/08.模块化/__pycache__/test01.cpython-37.pyc
    __builtins__ {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other o
    Point <class 'test01.Point'>
    p Point(x = 10,y = 20)
    ['Point', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'p']
    <class 'test01.Point'>
    {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.
    
    Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'copyright': Copyright (c) 2001-2017 Python Software Foundation.
    All Rights Reserved.
    
    Copyright (c) 2000 BeOpen.com.
    All Rights Reserved.
    
    Copyright (c) 1995-2001 Corporation for National Research Initiatives.
    All Rights Reserved.
    
    Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
    All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
        for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object.}
    /yinzhengjie/python/devops/python基础/08.模块化/__pycache__/test01.cpython-37.pyc
    None
    /yinzhengjie/python/devops/python基础/08.模块化/test01.py
    <_frozen_importlib_external.SourceFileLoader object at 0x1021610b8>
    test01
    
    ModuleSpec(name='test01', loader=<_frozen_importlib_external.SourceFileLoader object at 0x1021610b8>, origin='/yinzhengjie/python/devops/python基础/08.模块化/test01.py')
    Point(x = 10,y = 20)
    以上代码输出结果戳这里

    六.包

      pycharm中,创建Directory和创建Python package不同,前者是创建普通的目录,后者是创建一个带有 __init__.py 文件的目录即包。
    
      Python中,目录可以作为模块,这就是包,不过代码需要写在该目录下
    __init__.py 中。

    七.子模块

    1>.包目录下的py文件,子目录都是其子模块,目录结构如下图所示

    2>.在上图的包中“setup.py”文件编写测试代码

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 import hdfs
     7 import mapreduce.yarn
     8 from mapreduce import yarn
     9 from hdfs.namenode import NameNode
    10 
    11 print(__file__)         #打印当前文件名称
    12 
    13 print("{0}我是分割线{0}".format("*" * 20))   
    14 
    15 print(dir())
    16 
    17 print("{0}我是分割线{0}".format("*" * 20))
    18 
    19 import sys
    20 print(sorted(filter(lambda x:x.startswith("m"),sys.modules.keys()))) 
    in hadoop.hdfs
    in hadoop.yarn
    in haoop.hdfs.namenode
    /yinzhengjie/python/devops/python基础/08.模块化/hadoop/setup.py
    ********************我是分割线********************
    ['NameNode', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'hdfs', 'mapreduce', 'yarn']
    ********************我是分割线********************
    ['mapreduce', 'mapreduce.yarn', 'marshal']
    以上代码输出结果戳这里

     

    八.模块和包的总结

      包能够更好的组织模块,尤其是大的模块,其代码行数很多,可以把它拆分成很多子模块,便于使用某些功能就加载相应的子模块。
    
      包目录中
    __init__.py 是在包第一次导入的时候就会执行,内容可以为空,也可以是用于该包初始化工作的代码, 最好不要删除它(低版本不可删除 __init__.py 文件) 导入子模块一定会加载父模块,但是导入父模块一定不会导入子模块
      包目录之间只能使用.点号作为间隔符,表示模块及其子模块的层级关系
      模块也是封装,如同类、函数,不过它能够封装变量、类、函数。

      模块就是命名空间,其内部的顶层标识符,都是它的属性,可以通过
    __dict__ 或dir(module)查看。

      包也是模块,但模块不一定是包,包是特殊的模块,是一种组织方式,它包含 __path__ 属性
    from json import encoder 之后, json.dump 函数用不了,为什么? 
    
    import json.encoder 之后呢? json.dump 函数能用吗?
    
    原因是:
      from json import encoder之后,当前名词空间没有json,但是json模块已经加载过了,没有json的引用, 无法使用dump函数。
      import json.encoder也加载json模块,但是当前名词空间有json,因此可以调用json.dump。
    扩展小知识(使劲戳这里)

    九.绝对导入和相对导入

    1>.绝对导入

      在import语句或者from导入模块,模块名称最前面不是以.点开头的 

      绝对导入总是去模块搜索路径中找,当然会查看一下该模块是否已经加载

    2>.相对导入 

      只在包内使用,且只能用在from语句中,相对导入,更像是目录操作。
    
      使用.点号,表示当前目录内 
    
      ..表示上一级目录 不要在顶层模块中使用相对导入
    
      举例a.b.c模块,a、b是目录,c是模块c.py,c的代码中,使用 from . import d # imports a.b.d
        from .. import e # imports a.e
        from .d import x # a.b.d.x
        from ..e import x # a.e.x 
        ... 三点表示上上一级
    
      温馨提示:
          一旦一个模块中使用相对导入,就不可以作为主模块运行了。
          测试一下有相对导入语句的模块,能够直接运行吗?答案是否定的,很好理解,使用相对导入的模块就是为了内部互相的引用资源的,不是为了直接运行的,对于包来说,正确的使用方式还是在顶级模块使用这些包。

    十.访问控制

    使用 from xyz import * 导入
      1.如果模块没有 __all__from xyz import * 只导入非下划线开头的该模块的变量。如果是包,子模块也不 会导入,除非在 __all__ 中设置,或 __init__.py 中导入它们
      2.如果模块有 __all__from xyz import * 只导入 __all__ 列表中指定的名称,哪怕这个名词是下划线开头 的,或者是子模块
      3.from xyz import * 方式导入,使用简单,但是其副作用是导入大量不需要使用的变量,甚至有可能造成名 称的冲突。而 __all__ 可以控制被导入模块在这种导入方式下能够提供的变量名称,就是为了阻止from xyz import *导入过多的模块变量,从而避免冲突。因此,编写模块时,应该尽量加入 __all__
    
    from module import name1, name2 导入 
      这种方式的导入是明确的,哪怕是导入子模块,或者导入下划线开头的名称
      程序员可以有控制的导入名称和其对应的对象

    十一.模块变量的修改

      模块对象是同一个,因此模块的变量也是同一个,对模块变量的修改,会影响所有使用者。
    
      除非万不得已,或明确知道自己在做什么,否则不要修改模块的变量。
      前面学习过的猴子补丁,也可以通过打补丁的方式,修改模块的变量、类、函数等内容。
    #!/usr/bin/env python
    #_*_conding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie
    
    print(__name__)
    
    PI = 3.14
    test01.py内容
    #!/usr/bin/env python
    #_*_conding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie
    
    import test01 as t1
    
    print(t1.PI)
    test02.py内容
     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 import test01 as  t1
     7 
     8 print(t1.PI)
     9 t1.PI = 3.1415926
    10 
    11 import test02
    test01
    3.14
    3.1415926
    以上代码执行结果戳这里
  • 相关阅读:
    第五周作业
    2019春第四周作业编程总结
    2019春第四周作业
    2019春第二周作业编程总结
    2019春第一周作业编程总结
    自我认识
    对我影响最大的三位老师
    C语言I博客作业04
    C语言I博客作业03
    C语言I博客作业02
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/11809777.html
Copyright © 2020-2023  润新知