python:自定义模块并导入
自定义模块
自定义模块很简单,无非是使用任何编辑器保存一段Python代码。
自定义模块注意事项:
模块导入的注意事项:
示例:定义一个模块,在另外一个模块导入使用
定义my_module模块:
# my_module.py
def add(x, y):
return x + y
定义test模块:
# test.py
import my_module
result = my_module.add(1, 2)
print(result)
运行结果:
示例:导入的多个模块中功能名相同,调用的是后导入的
my_module1模块:
# my_module1.py
def say_hello():
print('你好,我是在my_module1的say_hello函数中')
my_module2模块:
# my_module2.py
def say_hello():
print('你好,我是在my_module2的say_hello函数中')
test模块:
# test.py
from my_module1 import say_hello
from my_module2 import say_hello
say_hello()
运行结果:
其实,PyCharm也给了我们提示,第1行导入变灰了:
测试自定义的模块:利用 __name__
变量的值是否等于'__main__'
进行判断
例如,自己写了my_module1模块,里边声明了say_hello函数,然后通过执行say_hello()来调用:
# my_module1.py
def say_hello():
print('你好,我是在my_module1的say_hello函数中')
say_hello()
运行结果:
存在的问题:
此时,无论是当前文件,还是其它导入了该模块的文件,在运行的时候,都会自动执行say_hello函数的调用。例如,在test模块中导入my_module1模块:
# test.py
from my_module1 import say_hello
运行:
可以发现,我们仅仅是导入my_module1模块,say_hello()就被执行了,而这不是我们所期望的。
解决方法:
使用__name__
变量的值进行判断:当直接运行这个模块的时候,__name__
变量的值等于 '__main__'
,而到被其它模块导入的时候,__name__
变量的值等于模块的名称。
my_module1模块代码修正后,只有当直接运行my_module1这个模块的时候,才会调用 say_hello()
;而当被其它模块导入的时候,不会调用 say_hello()
。
# my_module1.py
def say_hello():
print('你好,我是在my_module1的say_hello函数中')
if __name__ == '__main__':
say_hello()
__all__
变量
在Python中,__all__
是一个特殊的变量。如果在一个模块有 __all__
变量,当使用 from 模块名称 import *
导入时,只能导入 __all__
变量中列出的元素。
例如,定义一个模块my_module1,其中 __all__
变量的元素是’my_fun2’:
# my_module1.py
__all__ = ['my_fun2']
def my_fun1():
pass
def my_fun2():
pass
在另外一个模块test使用from my_module1 import *
导入,就只能使用my_fun2,而不能使用my_fun1,如果使用my_fun1,会报错:
# test.py
from my_module1 import *
my_fun1()
my_fun2()
运行:
其实,PyCharm中也给出了提示:
作者:听海边涛声