python基础:16.导包
0.前言
如果可以的话,请先关注(专栏和账号),然后点赞和收藏,最后学习和进步。你的支持是我继续写下去的最大动力,个人定当倾囊而送,不负众望。谢谢!!!
1.前提
基于win10专业版64位系统+64位jdk1.8+64位python3.6.5+社区版pycharm2018.1.3+unittest+selenium3.141.0。
要学好自动化测试,我们先从python语言基础开始学习,一步一个脚印,欲速则不达哦!
2.导包
python两种导包方式import和from...import。
在项目名称上鼠标右键选择新建一个包名为package1,在该包下面新建三个模块:
注:python中命名规则要求,包名和模块名小写,类名驼峰规则每个单次首字母大写,方法名驼峰规则第一个单次小写其它单次首字母大写。
模块1代码内容:
#直接定义方法
def method11():
print("我是模块module1中的方法method11")
def method12():
print("我是模块module1中的方法method12")
模块2代码内容:
#定义类方法
class ClassName2:
def method21(self):
print("我是模块module2中的类方法method21")
def method22(self):
print("我是模块module2中的类方法method22")
class ClassName3:
def method31(self):
print("我是模块module2中的类方法method31")
def method32(self):
print("我是模块module2中的类方法method32")
模块3中通过不同导包方式调用上面的方法。
1)import导包:包名.模块名
方式1:
import package1.module1
import package1.module2
if __name__ == '__main__':
package1.module1.method11()
package1.module1.method12()
package1.module2.ClassName2().method21()
package1.module2.ClassName3().method31()
#运行结果:
我是模块module1中的方法method11
我是模块module1中的方法method12
我是模块module2中的类方法method21
我是模块module2中的类方法method31
注:调用方法时每次都要加上包名.模块名,是否感觉到特别啰嗦?
方式2:重命名
import package1.module1 as m1
import package1.module2 as m2
if __name__ == '__main__':
m1.method11()
m1.method12()
m2.ClassName2().method21()
m2.ClassName3().method31()
#运行结果:
我是模块module1中的方法method11
我是模块module1中的方法method12
我是模块module2中的类方法method21
我是模块module2中的类方法method31
注:笔方式1好一点,as相当于重命名。
2)from 包名.模块名 import 方法名或者类名:
实现上面同样的执行结果。
方式1:分别导入
from package1.module1 import method11
from package1.module1 import method12
from package1.module2 import ClassName2
from package1.module2 import ClassName3
if __name__ == '__main__':
method11()
method12()
ClassName2().method21()
ClassName3().method31()
#运行结果:
我是模块module1中的方法method11
我是模块module1中的方法method12
我是模块module2中的类方法method21
我是模块module2中的类方法method31
方式2:同时导入多个
from package1.module1 import method11,method12
from package1.module2 import ClassName2,ClassName3
if __name__ == '__main__':
method11()
method12()
ClassName2().method21()
ClassName3().method31()
#运行结果:
我是模块module1中的方法method11
我是模块module1中的方法method12
我是模块module2中的类方法method21
我是模块module2中的类方法method31
方式3:导所有
from package1.module1 import *
from package1.module2 import *
if __name__ == '__main__':
method11()
method12()
ClassName2().method21()
ClassName3().method31()
#运行结果:
我是模块module1中的方法method11
我是模块module1中的方法method12
我是模块module2中的类方法method21
我是模块module2中的类方法method31
总结:
1)推荐使用倒数第二种导包方式,即同时导入多个;
2)倒数第一种方式虽然省事,但如果不同包下存在同名方法时可能会导致被相互覆盖的问题;
3)如果一个类要使用另外一个类中的部分属性和方法,建议导包方式用哪个导哪个;如果一个类要使用另外一个类中的所有属性和方法,建议使用继承的方式。