作业13

一、简述

  1.什么是模块

     模块就是在多个文件内分别存放不同的功能,存放功能的文件就叫做模块,而模块之间是可以相互导入调用的

  2.模块有哪些来源

    自定义模块:即我们自己创建一个文件然后将功能写入到文件的模块

    内置模块 :是Python解释器中自带的模块,是使用C语言编写的

    第三方模块:也属于自定义模块,不过是其他程序员已经编写好的模块,可以直接下载使用

    已经编译为DLL,C或C++的模块:这种模块我们不需要知道它的来历,只需要根据需求下载导入即可

  3.模块的格式有哪些

    取别名:将导入的模块命名一个新的名称方便使用  (import spam as newspam)

    导入多个模块:一次性将要用到的模块全部导入 (import spam,sys,time....)

    导入模块中某个名字到当前命名空间:(from spam import func  # 在当前命名空间可直接不加前缀调用spam的func函数)

    from取别名:等同于import取别名 (from spam import func as f)

    from导入多个模块:from spam import func,money,age....

    from导入模块中所有名称:from spam import * (若要导入的模块内的名字较多的情况下不建议使用,易产生名字冲突)

二、定义一个cuboid模块,模块中有三个变量长(long)宽(wide)高(high),数值自定义,有一个返回值为周长的perimeter的方法,一个返回值为表面积area的方法

 

cuboid文件内容:
long = 10
wide = 12
high = 13

def area(long,wide,high):
    res = (long*wide+long*high+wide*high)*2
    print(res)
    return res

def perimeter(long,wide,high):
    res = 4*(long+wide+high)
    print(res)
    return res

三、定义一个用户文件stul.py,在该文件中打印cuboid的长宽高,并获得周长和表面积,打印出来

 

stul.py文件内容:
import cuboid

print(cuboid.long, cuboid.wide, cuboid.high)
cuboid.perimeter(cuboid.long, cuboid.wide,cuboid.high)
cuboid.area(cuboid.long, cuboid.wide, cuboid.high)

四、在stu2.py文件中导入cuboid模块时为模块起一个简单的别名,利用别名完成第三题的操作

stu2.py文件内容:
import Practice as counts

print(counts.long, counts.wide, counts.high)
counts.perimeter(counts.long, counts.wide,counts.high)
counts.area(counts.long, counts.wide, counts.high)

五、现在有三个模块,sys、time、place,可以在run.py文件中导入三个模块吗?如果有那么有几种方式?写下来

 

1.
import sys
import time
import place

2.
import sys,time,place

六、结合第2、3、4题完成from...import...的案例,完成同样的功能

from cuboid import area as ar,perimeter as pe,long,wide,high
print(long,wide,high)
ar(10,12,13)
pe(10,12,13)

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

   import:优点:可以直接将模块内的所有文件全部导入

      缺点:使用时必须加前缀(模块名称)

  from ... import...:优点:可以将模块内的某个名字导入,直接使用名字即可,无需加前缀(模块名)

         :缺点:容易与当前执行文件的名字起冲突

posted @ 2018-10-11 21:19  BlackLinks  阅读(221)  评论(0编辑  收藏  举报