python import的一个很有意思的问题

今天有个很可爱的人问我一个看起来很简单的奇怪现象,看代码

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

是不会有输出的

 

这个例子告诉我们,女生是不讲道理的生物,自己领悟吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值