#demo.py
def say():
print("人生苦短,我学Python!")
def CLanguage():
print("C语言中文网:http://c.biancheng.net")
def disPython():
print("Python教程:http://c.biancheng.net/python")
#test.py
from demo import *
say()
CLanguage()
disPython()
执行 test.py 文件,输出结果为:
人生苦短,我学Python!
C语言中文网:http://c.biancheng.net
Python教程:http://c.biancheng.net/python
人生苦短,我学Python!
C语言中文网:http://c.biancheng.net
Traceback (most recent call last):
File "C:/Users/mengma/Desktop/2.py", line 4, in <module>
disPython()
NameError: name 'disPython' is not defined
举个例子,修改 demo.py 模块文件中的代码:也就是说,只有以“from 模块名 import *”形式导入的模块,当该模块设有 __all__ 变量时,只能导入该变量指定的成员,未指定的成员是无法导入的。
def say():
print("人生苦短,我学Python!")
def CLanguage():
print("C语言中文网:http://c.biancheng.net")
def disPython():
print("Python教程:http://c.biancheng.net/python")
__all__ = ["say","CLanguage"]
可见,__all__ 变量只包含 say() 和 CLanguage() 的函数名,不包含 disPython() 函数的名称。此时直接执行 test.py 文件,其执行结果为:
人生苦短,我学Python!
C语言中文网:http://c.biancheng.net
Traceback (most recent call last):
File "C:/Users/mengma/Desktop/2.py", line 4, in <module>
disPython()
NameError: name 'disPython' is not defined
#demo.py
def say():
print("人生苦短,我学Python!")
def CLanguage():
print("C语言中文网:http://c.biancheng.net")
def disPython():
print("Python教程:http://c.biancheng.net/python")
__all__ = ["say"]
#test.py
import demo
demo.say()
demo.CLanguage()
demo.disPython()
运行 test.py 文件,其输出结果为:
人生苦短,我学Python!
C语言中文网:http://c.biancheng.net
Python教程:http://c.biancheng.net/python
from demo import say from demo import CLanguage from demo import disPython say() CLanguage() disPython()运行 test.py,输出结果为:
人生苦短,我学Python!
C语言中文网:http://c.biancheng.net
Python教程:http://c.biancheng.net/python
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有