python常用模块:模块练习

原文链接: http://www.cnblogs.com/wuzhengzheng/p/9775173.html
今日作业:
 
1.简述
 
什么是模块
  模块就将一些函数功能封装在一个文件内,以‘文件名.py’命名,以“import 文件名”方式调用
 
模块有哪些来源
   自定义、内置、DLL编译器、包
模块的格式要求有哪些
  命名格式“文件名+.py” 调用格式有“import 函数名”或者“from xxx import xxx”
 
2.定义一个cuboid模块,模块中有三个变量长(long)宽(wide)高(high),数值自定义,有一个返回值为周长的perimeter方法,一个返回值为表面积的area方法
wide=3

high=4

def perimeter():
    return (long+wide+high)*4

def area():
    return long*wide*high
3.定义一个用户文件stu1.py,在该文件中打印cuboid的长宽高,并获得周长和表面积,打印出来
from cuboid import long,wide,high
print(long,wide,high)
import cuboid
res=cuboid.perimeter()
res1=cuboid.area()
print(res,res1)
 
4.在stu2.py文件中导入cuboid模块时为模块起简单别名,利用别名完成第3题中完成的操作
import cuboid as cub
print(long,high,wide)
res=cub.perimeter()
res1=cub.area()
print(res,res1)
5.现在有三个模块sys、time、place,可以在run.py文件导入三个模块吗?有几种方式?分别写出来
答:sys和time是内置函数,调用起冲突,只有place能正常调用,如果sys,time,place模块都不是内置函数,可以通过两种方式:import sys,time,place和将三个模块装入包内调用from models import *
 
6.结合第2、3、4题完成from...import...案例,完成同样的功能
from cuboid import long,wide,high
print(long,wide,high)

from cuboid import perimeter
print(perimeter())

from cuboid import area
print(area())

7.比较总结import与from...import...各自的优缺点

import
优点:模块与执行文件相对独立,调用不冲突
缺点:每次调用时都需要用到模块名+功能

form...import...
优点:每次调用不需要加模块名,节约内存
缺点:容易与被执行文件内的名称重复,冲突

转载于:https://www.cnblogs.com/wuzhengzheng/p/9775173.html

猜你喜欢

转载自blog.csdn.net/weixin_30438813/article/details/94880640