zoukankan      html  css  js  c++  java
  • Python学习笔记(6):模块

    我们已经知道函数可以重用代码,那么模块可以在其他程序中被重用,模块基本上就是一个包含了所有你定义的函数和变量的文件。Python的模块的文件名必须以.py为扩展名,导入模块用import语句。

    1. 使用sys模块

    import sys
    
    print("The command line arguments are:")
    for i in sys.argv:
        print(i)
    
    print("\n\nThe PYTHONPATH is", sys.path, "\n")
    

    2.字节编译的.pyc文件

    Python为了使输入模块更加快捷,将.py文件编译成字节文件.pyc。你只要使用import语句,后面跟文件名,即模块名,程序会自动生成一个同名的.pyc文件,下次你从别的程序导入这个模块的时候,.pyc文件就起作用了,它会快得多,这些字节编译的文件也与平台无关。

    3. from...import语句

    如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。

    4. 模块的__name__

    每个模块都有一个名称,在模块中可以通过语句来找出模块的名称。这在一个场合特别有用——就如前面所提到的,当一个模块被第一次输入的时候,这个模块的主块将被运行。假如我们只想在程序本身被使用的时候运行主块,而在它被别的模块输入的时候不运行主块,我们该怎么做呢?这可以通过模块的__name__属性完成。

    if __name__ == "__main__":
        print("This program is being run by itself")
    else:
        print("I am being imported from another module")
    

    5. 自定义模块

    # Filename: mymodule.py
    
    def sayHi():
        print("Hi, this is mymodule speaking.")
    
    version = "0.1"
    

    调用自定义模块

    import mymodule
    
    mymodule.sayHi()
    print(mymodule.version)
    

    输出结果:

    Hi, this is mymodule speaking.
    0.1

    6. dir()函数

    你可以使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。
    当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。

    >>> import sys
    >>> dir(sys)
    ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'int_info', 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'setcheckinterval', 'setfilesystemencoding', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
    >>>

  • 相关阅读:
    第03组 Alpha冲刺 总结
    第03组 Alpha冲刺 (6/6)
    第03组 Alpha冲刺 (5/6)
    第03组 Alpha冲刺 (4/6)
    第03组 Alpha冲刺 (3/6)
    第03组 Alpha冲刺 (2/6)
    第03组 Alpha冲刺 (1/6)
    第03组(63) 需求分析报告
    第03组(63) 团队展示
    第09组 Alpha冲刺 总结
  • 原文地址:https://www.cnblogs.com/known/p/1811379.html
Copyright © 2011-2022 走看看