(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.pswp.cn/news/391932.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391932.shtml
英文地址,請注明出處:http://en.pswp.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;最上面一層是頂層&…