zoukankan      html  css  js  c++  java
  • 面向对象之模块与包

    一 模块

     1  什么叫做模块:一个py文件就是一个模块

      模块的分类:内置模块,第三方模块和自定义模块

      内置模块:在python产生是就有的模块叫做内置模块,我们只管拿来调用即可

      第三方模块:别人已经定义好了的模块,我们只管下载安装一下就可以调用

      自定义模块:自己定义的模块叫做自定义模块,根据自己设置的调用方式调用

     2 导入模块的顺序:内置模块;第三方模块;自定义模块

      导入模块的规则是:建议不在同一行导入多个模块

      模块的命名空间:模块有模块的命名空间,存在于当前模块的py文件里

         在导入模块的第一时间就会创建模块的命名空间

     3 给模块重命名:as重命名  格式   :from 模块名 import  方法名  as  修改后的名字

    from lianxi import func1 as func_1
    func_1()
    

     

      *:是引用模块下面的所有功能,但是不能重命名   格式  :  from  模块名  import  *

       __all__=[ ]:与*号相通的,中括号里面的内容是啥,*号导入的功能就会相对应的。中括号里面的内容格式必须是字符串的格式。

      导入模块的几种格式:1  import  模块名

                2 from  模块名  import  具体功能名

                3 from  模块名  import  *

    # import lianxi
    # from lianxi import func
    # from lianxi import *
    

    如果导入的模块内容过长,却使用的功能很少,建议使用第二种的调用方式。

      模块与模块之间只要一次导入,就可以多次调用。

    import lianxi
    a=333
    def func():
        aa=lianxi.time.time()
        lianxi.time.sleep(1)
        print(444)
        print(lianxi.time.time()-aa)
    func()
    

     

     4 sys.modules:查看当前已经导入了的所有模块。

    import sys
    import lianxi
    a=333
    def func():
        aa=lianxi.time.time()
        lianxi.time.sleep(1)
        print(444)
        print(lianxi.time.time()-aa)
    func()
    print(sys.modules)
    
    
    
    结果是:
    {'builtins': <module 'builtins' (built-in)>, 'sys': <module 'sys' (built-in)>, '_frozen_importlib': <module '_frozen_importlib' (frozen)>, '_imp': <module '_imp' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_thread': <module '_thread' (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)>, 'nt': <module 'nt' (built-in)>, 'winreg': <module 'winreg' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>, 'encodings': <module 'encodings' from 'E:\python3.6\lib\encodings\__init__.py'>, 'codecs': <module 'codecs' from 'E:\python3.6\lib\codecs.py'>, '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from 'E:\python3.6\lib\encodings\aliases.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from 'E:\python3.6\lib\encodings\utf_8.py'>, '_signal': <module '_signal' (built-in)>, '__main__': <module '__main__' from 'E:/pycharm/pycharm/PyCharm Community Edition 2017.1.3/day27/练习.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from 'E:\python3.6\lib\encodings\latin_1.py'>, 'io': <module 'io' from 'E:\python3.6\lib\io.py'>, 'abc': <module 'abc' from 'E:\python3.6\lib\abc.py'>, '_weakrefset': <module '_weakrefset' from 'E:\python3.6\lib\_weakrefset.py'>, 'site': <module 'site' from 'E:\python3.6\lib\site.py'>, 'os': <module 'os' from 'E:\python3.6\lib\os.py'>, 'errno': <module 'errno' (built-in)>, 'stat': <module 'stat' from 'E:\python3.6\lib\stat.py'>, '_stat': <module '_stat' (built-in)>, 'ntpath': <module 'ntpath' from 'E:\python3.6\lib\ntpath.py'>, 'genericpath': <module 'genericpath' from 'E:\python3.6\lib\genericpath.py'>, 'os.path': <module 'ntpath' from 'E:\python3.6\lib\ntpath.py'>, '_collections_abc': <module '_collections_abc' from 'E:\python3.6\lib\_collections_abc.py'>, '_sitebuiltins': <module '_sitebuiltins' from 'E:\python3.6\lib\_sitebuiltins.py'>, 'sysconfig': <module 'sysconfig' from 'E:\python3.6\lib\sysconfig.py'>, 'lianxi': <module 'lianxi' from 'E:\pycharm\pycharm\PyCharm Community Edition 2017.1.3\day27\lianxi.py'>, 'time': <module 'time' (built-in)>}
    

      sys.path:查看导入模块的查找路径顺序

    import sys
    import lianxi
    a=333
    def func():
        aa=lianxi.time.time()
        lianxi.time.sleep(1)
        print(444)
        print(lianxi.time.time()-aa)
    func()
    print(sys.path)
    
    
    
    
    
    结果:
    ['E:\pycharm\pycharm\PyCharm Community Edition 2017.1.3\day27', 'E:\pycharm\pycharm2017pjb', 'E:\pycharm', 'E:\pycharm\pycharm\PyCharm Community Edition 2017.1.3', 'E:\python3.6\python36.zip', 'E:\python3.6\DLLs', 'E:\python3.6\lib', 'E:\python3.6', 'C:\Users\方杰\AppData\Roaming\Python\Python36\site-packages', 'E:\python3.6\lib\site-packages']
    

      导入的模块会被放在内存里,在导入的过程中对模块进行修改是没有作用的

      importlib.reload:在导入的过程中对模块进行修改,会起作用的。

     pyc文件是一个编译好了的文件,只有在导入模块的第一次就会产生,以后在导入模块就不会在产生pyc编译文件。

      python -m:强行产生一个pyc文件。

      5 name:当作脚本调用的时候结果就是__main__

      当name当做导入模块的时候,就是导入的模块名

      建议:调用一个函数的功能,结果和中间结果建议放在(if __name__=='__main__':)里面执行

    # def func_3(n):
    #     print(n)
    # if __name__=='__main__':
    #     func_3(10)
    

     6 dir函数:后面功能一个模块,将模块里的所有功能名字打印出来。

      builtins:内置的名字

    import builtins
    print(dir(builtins))
    
    
    结果:
    ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
    

     二  包

     1 什么叫做包:创建的目录里面有init.py文件,并且目录下面有很多的模块,这就叫做包。

        在不同的目录下导入包的格式: 格式1 绝对路径:from  路径.路径.....   import  模块名    

    from glance.api import policy
    policy.get()
    

                  导入的文件路径应该在from后面,并且用 .点 分开,导入的模块名跟在import的后面。

                     格式2 相对路径:from  ......目录名    import  模块名

           

      绝对路劲导入模块的好处是:在包的内部外部都能被执行

              坏处是:导入的路径会随着包与文件之间的关系变化而变化

      相对路径导入模块的好处是:一次写好的模块之间的导入关系,不需要关心这个包与文件之间的关系了

              坏处是:只能在这个包的内部调用

     如果自己写的模块与模块之间没有什么联系,就不需要去考虑相对路径和绝对路径了

      如果调用的是一整个包的时候,首先执行的是包下面的Z__init__.py文件。

      

      

  • 相关阅读:
    AngularJS Insert Update Delete Using PHP MySQL
    Simple task manager application using AngularJS PHP MySQL
    AngularJS MySQL and Bootstrap Shopping List Tutorial
    Starting out with Node.js and AngularJS
    AngularJS CRUD Example with PHP, MySQL and Material Design
    How to install KVM on Fedora 22
    Fake_AP模式下的Easy-Creds浅析
    河南公务员写古文辞职信
    AI
    政协委员:最大愿望是让小学生步行上学
  • 原文地址:https://www.cnblogs.com/fangjie0410/p/7570908.html
Copyright © 2011-2022 走看看