zoukankan      html  css  js  c++  java
  • 模块的 __name__

    模块的 __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__ 属性相同则代表这一模块是由用户独立运行的,因此我们便可以采取适当的行动。

  • 相关阅读:
    Merge Sorted Array
    Remove Duplicates from Sorted List
    Integer to Roman
    String to Integer (atoi)
    Valid Parentheses
    3Sum
    Remove Duplicates from Sorted Array
    Swap Nodes in Pairs
    得到一个Object的属性
    在WebGrid中做 批量删除操作
  • 原文地址:https://www.cnblogs.com/Davirain/p/8677964.html
Copyright © 2011-2022 走看看