品易云推流 关闭
文章详情页
文章 > Python基础教程 > Python不同模块下特殊变量的使用

Python不同模块下特殊变量的使用

python模块

头像

小妮浅浅

2021-09-06 10:01:212523浏览 · 0收藏 · 0评论

1、当模块(源文件)作为主程序运行,解释器将硬编码字符串赋值"__main__"给__name__变量。

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"

2、当模块被另一个导入时,导入语句中的名称分配给__name__变量。

假设某个其他模块是主程序并且它导入您的模块。这意味着在主程序或主程序导入的其他模块中有这样的语句:

# Suppose this is in some other main program.
import foo

解释器将搜索您的foo.py文件(以及搜索其他一些变体),并且在执行该模块之前。

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

以上就是Python不同模块下特殊变量的使用,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图