博客
关于我
__name__
阅读量:496 次
发布时间:2019-03-07

本文共 1528 字,大约阅读时间需要 5 分钟。

关于Python中的__name__变量解析scription.chars

In Python, the __name__ variable is a built-in variable that identifies the name of the module in which it is defined. This variable is particularly useful for debugging and understanding the structure of your program.

To demonstrate how __name__ works, let's look at some examples:

示例1: demo1.py

This script defines a function called printName(), and when executed directly, it will show the current module's name.

这样的情况可能,请看下文。
def printName():    print("Example1's __name__ is: " + __name__)

示例2: demo2.py

In this file, we import the printName function from demo1.py and execute it within the context of demo2.py. When running this script, the output will differ from the previous example.

import demo1if __name__ == '__main__':    printName()    print("Example2's __name__ is: " + __name__)

运行结果分析

运行上述脚本时,你会看到以下输出:

Example1's __name__ is: demo1

Example2's __name__ is: __main__

这个结果揭示了两件重要事情:

1. 当你在当前文件直接执行代码时,__name__变量将显示当前文件的名称。2. 当你从另一个文件导入函数并在该文件中执行时,__name__变量将显示__main__,这符合Python对模块执行行为的设计原则。

在PyCharm中如何运行

In PyCharm, you can right-click on your Python file (e.g., demo2.py) and select "Run demo2.py" from the context menu. This will execute the script and display the results in the console.

理解模块名称

Python使用模块化设计来组织代码,其中每个模块可以独立地包含功能。每个模块都有自己的__name__变量,其值取决于该模块如何被调用:

  • 主模块:当你直接运行一个文件时,该文件被称为"主模块"。在这种情况下,__name__变量将显示文件名(不带.py扩展名)。
  • 导入模块:当你从一个文件中导入函数或代码片段到主模块时,该文件被称为导入模块。在这种情况下,__name__变量将显示文件名(不带.py扩展名)。

总结

通过以上示例,我们可以清晰地看到__name__变量在不同情况下的行为。理解这一点对于调试和优化你的Python程序是非常重要的。

转载地址:http://egncz.baihongyu.com/

你可能感兴趣的文章
mysql replace first,MySQL中处理各种重复的一些方法
查看>>
MySQL replace函数替换字符串语句的用法(mysql字符串替换)
查看>>
mysql replace用法
查看>>
Mysql Row_Format 参数讲解
查看>>
mysql select, from ,join ,on ,where groupby,having ,order by limit的执行顺序和书写顺序
查看>>
MySQL Server 5.5安装记录
查看>>
mysql server has gone away
查看>>
mysql slave 停了_slave 停止。求解决方法
查看>>
MySQL SQL 优化指南:主键、ORDER BY、GROUP BY 和 UPDATE 优化详解
查看>>
MYSQL sql语句针对数据记录时间范围查询的效率对比
查看>>
mysql sum 没返回,如果没有找到任何值,我如何在MySQL中获得SUM函数以返回'0'?
查看>>
mysql Timestamp时间隔了8小时
查看>>
Mysql tinyint(1)与tinyint(4)的区别
查看>>
mysql union orderby 无效
查看>>
mysql v$session_Oracle 进程查看v$session
查看>>
mysql where中如何判断不为空
查看>>
MySQL Workbench 使用手册:从入门到精通
查看>>
mysql workbench6.3.5_MySQL Workbench
查看>>
MySQL Workbench安装教程以及菜单汉化
查看>>
MySQL Xtrabackup 安装、备份、恢复
查看>>