模块定义
什么是模块:一个py文件就是一个模块
模块分为三类:
内置模块,(标准库):.python解释器自带的,time,os,sys,等等.200多种.
自定义模块:自己写的模块
第三方库(模块):各种大神写的一些模块,通过pip install....安装.6000种.
模块的引入
import引用模块发生三件事.
1. 将模块名.py文件加载到内存.
2. 在内存中创建一个以模块名命名的名称空间.
3. 通过模块名,名称空间的名字.等方式引用此模块的名字(变量,函数名,类名等等).
1.通过import 引用模块和起别名
通过import 引用模块 他有自己的独立名称空间,与当前执行文件没有关系.
import 模块名 as 别名 such as import pandas as pd import numpy as np
2.from...import....
相当于从(模块名)模块的全局空间中将变量与值的对应关系,复制到当前执行文件的全局名称空间中.
3.from ... import * 与__all__配合使用
3.1导入该模块时,只能导入__all__中的变量,方法和类
beimported.py 文件:
#beimported.py __all__=('A','func') #在别的模块中,导入该模块时,只能导入__all__中的变量,方法和类 class A(): def __init__(self,name,age): self.name=name self.age=age class B(): def __init__(self,name,id): self.name=name self.id=id def func(): print('func() is called!') def func1(): print('func1() is called!')
#test.py from beimpoted2 import * #kk.py中定义了__all__属性,只能导入__all__中定义的属性,方法和类 a=A('python','24') print(a.name,a.age) #'python','24' func() #'func() is called!' func1() #NameError: name 'func1' is not defined b=B('python',123456) #NameError: name 'B' is not defined
3.2import * 方式只能导入公有的属性,方法或类【无法导入以单下划线开头(protected)或以双下划线开头(private)的属性,方法或类】,但是在all中的除外。
beimpoted2.py 文件
#beimported2.py def func(): #模块中的public方法 print('func() is called!') def _func(): #模块中的protected方法 print('_func() is called!') def __func():#模块中的private方法 print('__func() is called!')
from beimported2 import * #这种方式只能导入公有的属性,方法或类【无法导入以单下划线开头(protected)或以双下划线开头(private)的属性,方法或类】 func() #'func() is called!' _func() #NameError: name '_func' is not defined __func() #NameError: name '__func' is not defined
beimported3.py文件
# beimported3.py __all__=('func1','__func1','_A1') #放入__all__中所有属性均可导入,即使是以下划线开头 class _A1(): def __init__(self,name): self.name=name def func1(): print('func() is called!') def func2(): print('func2() is called!') def _func1(): print('_func() is called!') def __func1(): print('__func() is called!)
from beimported3 import * func() func1() #func1不在__all__中,无法导入 NameError: name 'func1' is not defined _func() #_func不在__all__中,无法导入 NameError: name '_func' is not defined __func() #__func在__all__中,可以导入 a=_A('python') #_A在__all__中,可以导入 print(a.name) #python
3.3通过import 模块 ,调用模块名.方法 这种方式导入public,protected,private
beimported4文件
#beimported4 def func(): print('func() is called!') def _func(): print('_func() is called!') def __func(): print('__func() is called!')
from beimported4 import func,_func,__func #可以通过这种方式导入public,protected,private func() #'func() is called!' _func() #NameError: name '_func' is not defined __func() #NameError: name '__func' is not defined
import beimported4 #也可以通过这种方式导入public,protected,private beimported4.func() beimported4._func() #NameError: name '_func' is not defined beimported4.__func() #NameError: name '__func' is not defined
3.4排除 模块多层引入:
#beimported5.py import sys __all__ = ["func"] # 排除了 'sys' def func(): print('func() is called!')
#test.py from beimported5 import * #print(sys.path) #NameError: name 'sys' is not defined func()
vs :