python模块中的__name__使用

来源:互联网 发布:手机校色软件 编辑:程序博客网 时间:2024/04/30 04:05

在python中当一个模块引用另外一个模块的时候,被引用的这个模块的主题会先整体运行,但是在有的情况下,不想让引用的模块里面的方法都运行,只运行引用的它的方法,那怎么办呢,那就用到__name__属性了,话不多说,见如下代码。

被引用模块代码:

# -*- coding: utf-8 -*-def sayHello():    print 'Hello World'if __name__ == '__main__':    sayHello()def func(a,b=5,c=10):    print 'a is', a, 'and b is', b, 'and c is', c

引用模块代码:

# -*- coding: utf-8 -*-import function1 as ff.func(3, 7)f.func(25, c=24)f.func(c=50,a=100)

以上代码如果在没有__name__属性的判断下,输出如下:

Hello Worlda is 3 and b is 7 and c is 10a is 25 and b is 5 and c is 24a is 100 and b is 5 and c is 50

加上判断之后,输出如下:

a is 3 and b is 7 and c is 10a is 25 and b is 5 and c is 24a is 100 and b is 5 and c is 50

结果一看就很明显了。。


0 0
原创粉丝点击