欢迎来到@一夜看尽长安花 博客,您的点赞和收藏是我持续发文的动力
对于文章中出现的任何错误请大家批评指出,一定及时修改。有任何想要讨论的问题可联系我:3329759426@qq.com 。发布文章的风格因专栏而异,均自成体系,不足之处请大家指正。
专栏:
文章概述:对创建自己的module模块以及__init__脚本的作用的介绍
关键词:创建自己的module模块 __init__脚本的作用
本文目录:
Python之__init__.py
在同一个包下创建一个functionality模块
def add(x, y):
return x+y
def sub(x, y):
return x-y
def mul(x, y):
return x*y
def div(x, y):
return x/y
让我们在另一个包othermodule中创建一个second.py
脚本文件
def myfunction():
print("Hello")
让我们在othermodule中再创建一个third.py
脚本文件
def another_function():
print("ABC")
切换到main.py
,这里我们试图导入othermodule文件夹下的所有脚本
想模仿导入同一个包里的模块下所用的所有函数来导入不同包下的所有模块
导入othermodule文件夹下的所有脚本:
from functionality import *
from othermodule import *
print(add(10, 20))
print(sub(10, 20))
second.myfunction()
这里就会报错了,这就是为什么需要__init__.py
!
让我们在othermodule文件夹下创建__init__.py
脚本,这时这个文件夹就变成了一个python模块!__init__.py
脚本中可以写如下
__all__ = ["second", "third"]
写上这一行的话,我们之前的导入代码就生效了,
原理就是在主脚本中的魔法方法__init__调用了这个__init__.py的脚本,识别了所有的模块名
from functionality import *
from othermodule import *
print(add(10, 20))
print(sub(10, 20))
#调用方法
second.myfunction()
logo也有变化!
----->
中间多出来了一个圆圈
如果我们像直接使用方法名调用,不想还加上模块名
可以进一步改进__init__脚本
格式如下: from .模块名 import 函数名
这个‘’.‘’表示当前文件夹下
__all__ = ["second", "third"]
from .second import myfunction
from .third import another_function
然后我们还需要做一个导入操作
格式如下:from 包名 import 函数名
from othermodule import myfunction
from othermodule import another_function
这样就可以直接使用函数啦!
from functionality import *
from othermodule import myfunction
from othermodule import another_function
print(add(10, 20))
myfunction()
another_function()
创建子模块
我们可以在模块中创建子模块,比如我们在othermodule(文件夹)模块下创建一个submodule文件夹,在submodule文件夹下创建一个脚本fourth.py
def last_fct():
print("fourth")
切换到main.py
,
from functionality import *
#两种调用方法
from othermodule.submodule import fourth
from othermodule.submodule.fourth import last_fct
print(add(10, 20))
print(sub(10, 20))
fourth.last_fct()
last_fct()
还有一个就是在__init__.py
脚本中还可以写导入
__all__ = ["second", "third"]
from .second import myfunction
from .third import another_function
from .submodule.fourth import last_fct
再导入一下
from othermodule import last_fct
这样也可以直接使用last_fct() 函数啦!
到此为止,我们就可以开发自己的模块了!