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

版权声明:本文为博主原创文章,未经允许,不得转载,如需转载请注明出处 https://blog.csdn.net/ssjdoudou/article/details/83627202

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

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

是不会有输出的

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

猜你喜欢

转载自blog.csdn.net/ssjdoudou/article/details/83627202