(Python的)__ name__中包含什么?

_名称_变量及其在Python中的用法简介 (An introduction to the _ _name_ _ variable and its usage in Python)

You’ve most likely seen the __name__ variable when you’ve gone through Python code. Below you see an example code snippet of how it may look:

通过Python代码,您最有可能看到了__name__变量。 在下面,您可以查看其外观的示例代码片段:

if __name__ == '__main__':    main()

In this article, I want to show you how you can make use of this variable to create modules in Python.

在本文中,我想向您展示如何利用此变量在Python中创建模块。

为什么使用_名称_变量? (Why is the _ _name_ _ variable used?)

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script.

__name__变量(前后两个下划线)是一个特殊的Python变量。 它的取值取决于我们执行包含脚本的方式。

Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.

有时,您编写的脚本所包含的功能可能在其他脚本中也很有用。 在Python中,您可以将该脚本作为另一个脚本中的模块导入。

Thanks to this special variable, you can decide whether you want to run the script. Or that you want to import the functions defined in the script.

借助此特殊变量,您可以决定是否要运行脚本。 或者您要导入脚本中定义的功能。

__name__变量可以包含哪些值? (What values can the __name__ variable contain?)

When you run your script, the __name__ variable equals __main__. When you import the containing script, it will contain the name of the script.

运行脚本时, __name__变量等于__main__ 。 导入包含脚本时,它将包含脚本的名称。

Let us take a look at these two use cases and describe the process with two illustrations.

让我们看一下这两个用例,并用两个插图描述该过程。

方案1-运行脚本 (Scenario 1 - Run the script)

Suppose we wrote the script nameScript.py as follows:

假设我们编写了脚本 nameScript.py如下:

def myFunction():    print 'The value of __name__ is ' + __name__
def main():    myFunction()
if __name__ == '__main__':    main()

If you run nameScript.py, the process below is followed.

如果运行nameScript.py,则遵循以下过程。

Before all other code is run, the __name__ variable is set to __main__. After that, the main and myFunction def statements are run. Because the condition evaluates to true, the main function is called. This, in turn, calls myFunction. This prints out the value of __main__.

在运行所有其他代码之前,将__name__变量设置为__main__。 之后, main myFunction def语句运行。 因为条件的计算结果为true,所以将调用main函数。 依次调用myFunction。 这将打印出__main__的值。

方案2-将脚本导入另一个脚本 (Scenario 2 - Import the script in another script)

If we want to re-use myFunction in another script, for example importingScript.py, we can import nameScript.py as a module.

如果要在另一个脚本中重新使用myFunction,例如importingScript.py ,则可以将nameScript.py导入为模块。

The code in importingScript.py could be as follows:

importingScript.py的代码可能如下:

import nameScript as ns
ns.myFunction()

We then have two scopes: one of importingScript and the second scope of nameScript. In the illustration, you’ll see how it differs from the first use case.

然后,我们有两个作用域:一个是importingScript ,另一个是nameScript 。 在图中,您将看到它与第一个用例有何不同。

In importingScript.py the __name__ variable is set to __main__. By importing nameScript, Python starts looking for a file by adding .py to the module name. It then runs the code contained in the imported file.

在importingScript.py中, __name__变量设置为__main__。 通过导入nameScript,Python通过在模块名称中添加.py开始查找文件。 然后,它将运行导入文件中包含的代码。

But this time it is set to nameScript. Again the def statements for main and myFunction are run. But, now the condition evaluates to false and main is not called.

但是这次 设置为nameScript。 再次运行main和myFunction的def语句。 但是,现在条件评估为false且main不被调用。

In importingScript.py we call myFunction which outputs nameScript. NameScript is known to myFunction when that function was defined.

在importingScript.py中,我们调用myFunction来输出nameScript。 定义函数时,myFunction知道NameScript。

If you would print __name__ in the importingScript, this would output __main__. The reason for this is that Python uses the value known in the scope of importingScript.

如果要在importingScript中打印__name__ ,则将输出__main__ 。 原因是Python使用importingScript范围内的已知值。

结论 (Conclusion)

In this short article, I explained how you can use the __name__ variable to write modules. You can also run these modules on their own. This can be done by making use of how the values of these variables change depending on where they occur.

在这篇简短的文章中,我解释了如何使用__name__变量编写模块。 您也可以单独运行这些模块。 这可以通过利用这些变量的值根据它们发生的位置如何变化来完成。

翻译自: https://www.freecodecamp.org/news/whats-in-a-python-s-name-506262fe61e8/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391932.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

毕业论文计算机附录模板,毕业论文格式是什么,附录又是什么?

毕业论文格式是什么,附录又是什么?附录对论文内用起到一个补充说明的作用,附录应属于论文的正文,有的论文需要写明,有的论文可能不需要写,大多数情况是不需要写的,附录的位置一般放在论文的结尾处&#xf…

文件上传速度查询方法

由于业务迁移,需要将大量文件拷贝到目标机器上的/mnt目录,在拷贝过程中,想要查看上传的速度,做法如下:[rootmail01 ~]# du -sh /mnt5.6G /mnt[rootmail01 ~]# watch -n1 du -sm /mnt/ #会出现下面的一屏现象 …

spring—AOP 的动态代理技术

AOP 的动态代理技术 常用的动态代理技术 JDK 代理 : 基于接口的动态代理技术 cglib 代理:基于父类的动态代理技术 JDK 代理 public class proxy {Testpublic void test() {final ImplDao dao new ImplDao();Dao pro (Dao) Proxy.newProxyInstance(ImplDao.cl…

非常详细的Django使用Token(转)

基于Token的身份验证 在实现登录功能的时候,正常的B/S应用都会使用cookiesession的方式来做身份验证,后台直接向cookie中写数据,但是由于移动端的存在,移动端是没有cookie机制的,所以使用token可以实现移动端和客户端的token通信。 验证流程 整个基于Token的验证流程如下: 客户…

Java中获取完整的url

HttpServletRequest httpRequest(HttpServletRequest)request; String strBackUrl "http://" request.getServerName() //服务器地址 ":" request.getServerPort() //端口号 httpRequest.getContextPath() //项目名称 httpRequ…

数据科学中的数据可视化

数据可视化简介 (Introduction to Data Visualization) Data visualization is the process of creating interactive visuals to understand trends, variations, and derive meaningful insights from the data. Data visualization is used mainly for data checking and cl…

打针小说软件测试,UPDATE注射(mysql+php)的两个模式

一.---- 表的结构 userinfo--CREATE TABLE userinfo (groudid varchar(12) NOT NULL default 1,user varchar(12) NOT NULL default heige,pass varchar(122) NOT NULL default 123456) ENGINEMyISAM DEFAULT CHARSETlatin1;---- 导出表中的数据 userinfo--INSERT INTO userinf…

前端速成班_在此速成班中学习Go

前端速成班Learn everything you need to get started programming in Go with this crash course tutorial.通过该速成课程教程,学习在Go中开始编程所需的一切。 First, learn how to install a Go Programming Environment on Windows, Mac, or Linux. Then, lea…

手把手教你webpack3(6)css-loader详细使用说明

CSS-LOADER配置详解 前注: 文档全文请查看 根目录的文档说明。 如果可以,请给本项目加【Star】和【Fork】持续关注。 有疑义请点击这里,发【Issues】。 1、概述 对于一般的css文件,我们需要动用三个loader(是不是觉得好…

shell远程执行命令

1、先要配置免密登陆&#xff0c;查看上一篇免密传输内容 2、命令行执行少量命令&#xff1a;ssh ip "command1;command2"。例&#xff1a;ssh 172.1.1.1 "cd /home;ls" 3、脚本批量执行命令&#xff1a; #&#xff01;/bin/bash ssh ip << remotes…

Python调用C语言

Python中的ctypes模块可能是Python调用C方法中最简单的一种。ctypes模块提供了和C语言兼容的数据类型和函数来加载dll文件&#xff0c;因此在调用时不需对源文件做任何的修改。也正是如此奠定了这种方法的简单性。 示例如下 实现两数求和的C代码&#xff0c;保存为add.c //samp…

多重线性回归 多元线性回归_了解多元线性回归

多重线性回归 多元线性回归Video Link影片连结 We have taken a look at Simple Linear Regression in Episode 4.1 where we had one variable x to predict y, but what if now we have multiple variables, not just x, but x1,x2, x3 … to predict y — how would we app…

tp703n怎么做无线打印服务器,TP-Link TL-WR703N无线路由器无线AP模式怎么设置

TP-Link TL-WR703N无线路由器配置简单&#xff0c;不过对于没有网络基础的用户来说&#xff0c;完成路由器的安装和无线AP模式的设置&#xff0c;仍然有一定的困难&#xff0c;本文学习啦小编主要介绍TP-Link TL-WR703N无线路由器无线AP模式的设置方法!TP-Link TL-WR703N无线路…

unity 克隆_使用Unity开发Portal游戏克隆

unity 克隆Learn game development principles by coding a Portal-like game using Unity and C#. The principles you learn in this lecture from Colton Ogden can apply to any programming language and any game.通过使用Unity和C&#xff03;编写类似于Portal的游戏来学…

swift基础学习(八)

####1.主要用到的知识点 CAGradientLayer 处理渐变色AVAudioPlayer 音频播放Timer 定时器CABasicAnimation 动画#####2.效果图 ####3.代码 import UIKit import AVFoundationclass ViewController: UIViewController, AVAudioPlayerDelegate {var gradientLayer: CAGradientLay…

pandas之groupby分组与pivot_table透视

一、groupby 类似excel的数据透视表&#xff0c;一般是按照行进行分组&#xff0c;使用方法如下。 df.groupby(byNone, axis0, levelNone, as_indexTrue, sortTrue, group_keysTrue,squeezeFalse, observedFalse, **kwargs) 分组得到的直接结果是一个DataFrameGroupBy对象。 df…

js能否打印服务器端文档,js打印远程服务器文件

js打印远程服务器文件 内容精选换一换对于密码鉴权方式创建的Windows 2012弹性云服务器&#xff0c;使用初始密码以MSTSC方式登录时&#xff0c;登录失败&#xff0c;系统显示“第一次登录之前&#xff0c;你必须更改密码。请更新密码&#xff0c;或者与系统管理员或技术支持联…

spring—JdbcTemplate使用

JdbcTemplate基本使用 01-JdbcTemplate基本使用-概述(了解) JdbcTemplate是spring框架中提供的一个对象&#xff0c;是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。例如&#xff1a;操作关系型数据的JdbcTemplate和HibernateTemplate&…

vanilla_如何在Vanilla JavaScript中操作DOM

vanillaby carlos da costa通过卡洛斯达科斯塔 如何在Vanilla JavaScript中操作DOM (How to manipulate the DOM in Vanilla JavaScript) So you have learned variables, selection structures, and loops. Now it is time to learn about DOM manipulation and to start doi…

NOIP201202寻宝

题目 试题描述传说很遥远的藏宝楼顶层藏着诱人的宝藏。 小明历尽千辛万苦终于找到传说中的这个藏宝楼&#xff0c;藏宝楼的门口竖着一个木板&#xff0c;上面写有几个大字&#xff1a;寻宝说明书。说明书的内容如下&#xff1a;藏宝楼共有N1层&#xff0c;最上面一层是顶层&…