小白教程

 找回密码
 立即注册

from..import语句

发布者: 小白教程

如果要将argv变量直接导入程序中(以避免sys.每次都键入变量),则可以使用该from sys import argv语句。

警告:通常,避免使用该from..import语句,而应使用该import语句。这是因为您的程序将避免名称冲突,并且更具可读性。

例子:

from math import sqrt
print("Square root of 16 is", sqrt(16))

一个模块的 __name__

每个模块都有一个名称,模块中的语句可以找出其模块的名称。对于确定模块是独立运行还是导入的特定目的,这非常方便。如前所述,第一次导入模块时,将执行其中包含的代码。我们可以使用它来使模块以不同的方式运行,具体取决于它是自己使用还是从另一个模块导入。这可以使用__name__模块属性来实现

示例(另存为module_using_name.py):

if __name__ == '__main__':
    print('This program is being run by itself')
else:
    print('I am being imported from another module')

输出:

$ python module_using_name.py
This program is being run by itself

$ python
>>> import module_using_name
I am being imported from another module
>>>

这个怎么运作

每个Python模块都有其__name__定义。如果为'__main__',则表示该模块由用户独立运行,我们可以采取适当的措施。

上一篇:模块下一篇:制作自己的模块

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:35 , Processed in 0.022867 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部