python import的一个很有意思的问题
程序员文章站
2022-03-12 16:01:12
...
今天有个很可爱的人问我一个看起来很简单的奇怪现象,看代码
def print_models(unprinted_design,completed_models):
"""模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其打印到列表completed_models中
"""
while unprinted_design:
current_design=unprinted_design.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model:"+current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
if __name__ == '__main__':
'''unprinted_designs = ['11','22','33']
completed_models = []
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)'''
unprinted_designs = ['11', '22', '33']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
别管这个是干嘛的,先看结果
Printing model:33
Printing model:22
Printing model:11
The following models have been printed:
33
22
11
Process finished with exit code 0
到这里没什么,这个py我们命名为uuu
然后我新建了一个yyy.py,里面只有一行代码
from uuu import print_models as pm
引入uuu里的一个函数,可是奇怪的是,运行完这个yyy之后,输出和运行uuu的一样!
Printing model:33
Printing model:22
Printing model:11
The following models have been printed:
33
22
11
Process finished with exit code 0
明明我们连参数都没给啊?
这是因为,我们引入py文件的时候,被引入的py文件一定要有主函数入口
if __name__ == '__main__':
就是这个东东,没有这个,引入该py文件的时候会编译该py文件所有非函数的代码,而事实上我们一般只需要调用其中的函数即可,上面这个例子,没有主函数的时候,底下调用参数运行函数的代码也被执行了,所以会有和uuu一样的输出。
那么应该怎么做呢
def print_models(unprinted_design,completed_models):
"""模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其打印到列表completed_models中
"""
while unprinted_design:
current_design=unprinted_design.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model:"+current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
if __name__ == '__main__':
unprinted_designs = ['11','22','33']
completed_models = []
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
'''unprinted_designs = ['11', '22', '33']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)'''
输出结果如下:
Process finished with exit code 0
是不会有输出的
这个例子告诉我们,女生是不讲道理的生物,自己领悟吧。
上一篇: css3哪个属性改变层叠性
推荐阅读
-
Python中import导入上一级目录模块及循环import问题的解决
-
python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
-
解决python给列表里添加字典时被最后一个覆盖的问题
-
python爬虫 下载一个网页内的图片解决分页以及图片懒加载的问题
-
Python中import导入上一级目录模块及循环import问题的解决
-
解决python3 安装完Pycurl在import pycurl时报错的问题
-
一个有意思的js块作用域问题
-
python中from module import * 的一个坑
-
Python实现的生成自我描述脚本分享(很有意思的程序)
-
解决Python import .pyd 可能遇到路径的问题