Skip to content

[问题] 如何理解 if __name__ == '__main__'? #20

@ShannonChenCHN

Description

@ShannonChenCHN
  • __name__ 是内置变量,用于表示当前模块的名字,同时还能反映一个包的结构。
  • __main__ 表示的是当前模块是直接执行的,而不是被导入的。因为 Python 不像 C 这类语言有 main 函数作为入口函数,Python 的每个文件可以单独执行。

示例

文件 download.py 中的代码如下:

def get_images():
    return ['logo', 'tree', 'mountain']

def download_images():
    pass

if __name__ == '__main__':
    download_images()

文件 print.py 中的代码如下:

import download  # 引入 download 模块

def print_images():
     images = download.get_images()
     for image_name in images:
         print(image_name)

参考

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions