python3.7入门系列九 模块

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bowei026/article/details/90107266

当写的函数越来越多的时候,通常我们会按模块来组织函数,功能相关的函数放在一个模块中。对应python来说一个模块保存在一个独立文件中。
使用的时候导入这个模块,就可以使用模块的函数了
例如,将下面的函数保存到 hello.py 文件中
def hi(name):
    return 'hi, ' + name

然后再新建一个 main.py 文件, 内容如下
from hello import hi

message = hi('Tome')
print(message)
执行这个文件,运行结果:
hi, Tome

这里 hello.py 就是一个模块hello, 引用hello模块的hi方法 from hello import hi, 也可以导入整个模块:
import hello

message = hello.hi('Tome')
print(message)
这里引用了模块hello,这种情况在使用hi函数时就要带上模块名 hello.hi('Tom'), 还可以导入模块的所有函数;
from hello import *

message = hi('Tome')
print(message)
这里 from hello import * 引入了hello模块的所有函数,此时引用里面的函数不需要加上模块名,但是不推荐这么使用,因为很容易出现相同的函数名而造成函数冲突

用as 给模块 或 函数取别名
将函数hi重命名为 welcome
from hello import hi as welcome

message = welcome('Tome')
print(message)

将模块 hi 取别名为 welcome
import hello as welcome

message = welcome.hi('Tome')
print(message)

本文内容到此结束,更多内容可关注公众号和个人微信号:

猜你喜欢

转载自blog.csdn.net/bowei026/article/details/90107266