python基础--模块

一、模块是一个包含全部你定义的函数和变量的文件,其后缀名是.py。python

  模块能够被别的程序引入,以使用该模块中的函数等功能。这也是使用 python 标准库的方法。app

  例子:sys.argv 是一个包含命令行参数的列表函数

import sys
 
print('命令行参数以下:')
for i in sys.argv:
   print(i)
 
print('\n\nPython 路径为:', sys.path, '\n')

 

二、导入本身写的模块importui

  定义test.pyspa

def method():
    print("method...")

  定义hello.py.net

import test
 
test.method()

  test.py和hello.py在同一目录下,执行python .\hello.py,报错 ModuleNotFoundError: No module named 'test'命令行

 

  import导入模块时的搜索路径code

    打印sys.path结果:blog

    - Python 路径为: ['D:\\DevTools\\python-3.7.4-embed-amd64\\python37.zip', 'D:\\DevTools\\python-3.7.4-embed-amd64']ip

    - sys.path 输出是一个列表,第一项是空串,表明当前目录;我本地安装的Python的sys.path第一项不是空串

 

  了解了搜索路径的概念,就能够在脚本中修改sys.path来引入一些不在搜索路径中的模块:sys.path(环境变量)

   修改hello.py

import sys
sys.path.append("D:\python\demo")
import test
 
test.method()

 

三、from … import 语句

  from modulename import  name1, name2...

  from modulename import *

 

四、__name__属性

  __name__: 每一个模块都有一个__name__属性,当其值是'__main__'时,代表该模块自身在运行,不然是被引入。

 

五、dir()函数

  内置的函数 dir() 能够找到模块内定义的全部名称。以一个字符串列表的形式返回:

  print(dir(test))结果:['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'method']

 

六、包

 

  hello.py

import sys
sys.path.append("D:\python\demo")
import a.b.test
 
a.b.test.method()

  test.py

def method():
    print("method...")

  经过import a.b.test这样导入模块,使用的使用也要带包。可使用as关键字将导入的模块从新命名,好比

 

import sys
sys.path.append("D:\python\demo")
import a.b.test as test
 
test.method()

 

  还有一种导入子模块的方法是:

import sys
sys.path.append("D:\python\demo")
from a.b import test
 
test.method()

  还有一种变化就是直接导入一个函数或者变量:

import sys
sys.path.append("D:\python\demo")
from a.b.test import method
 
method()

 

七、__all__

  从一个包中导入* ,被导入的模块最好使用__all__来指定导入的内容(好比函数或变量)。

  test.py

__all__ = ["method", "method2"]

def method():
    print("method...")
def method2():
    print("method2...")

def main():
    method()
    method2()

if __name__ == '__main__':
    main()

  hello.py

import sys
sys.path.append("D:\python\demo")
from a.b.test import *
 
method()
method2()

 

八、__init__.py和__all__的使用

 

   __init__.py

__all__ = ["test"]
from . import test

  test.py

__all__ = ["method", "method2"]

def method():
    print("method...")
def method2():
    print("method2...")

def main():
    method()
    method2()

if __name__ == '__main__':
    main()

  main.py

import sys
sys.path.append("D:\python\demo")

# import a
# a.test.method()

from a import *
test.method()
相关文章
相关标签/搜索