搜尋
首頁後端開發Python教學深入解析Python中的__builtins__内建对象

如果你已经学习了包,模块这些知识了。
你会不会有好奇:Python为什么可以直接使用一些内建函数,不用显式的导入它们,比如 str() int() dir() ...?
原因是Python解释器第一次启动的时候 __builtins__ 就已经在命名空间了(Note: 有s)

进Shell看看:

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, 
'__name__': '__main__', '__doc__': None, '__package__': None}


你可以再次导入 __builtin__(Note: 没有s):

import __builtin__
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, 
'__name__': '__main__', '__doc__': None, '__builtin__': 
<module '__builtin__' (built-in)>, '__package__': None}


这时候多了一个 __builtin__ 对象,你可以判断它们是不是相同的:

>>> __builtin__ is __builtins__
True
>>> type(__builtin__)
<type 'module'>
>>> type(__builtins__)
<type 'module'>


现在我们把它从一个文件导入:

# file1.py
import __builtin__

print "module name __name__ : ", __name__
print "__builtin__ is __builtins__: ", __builtin__ is __builtins__
print "type(__builtin__): ", type(__builtin__)
print "type(__builtins__): ", type(__builtins__)
print "__builtins__ is __builtin__.__dict__", __builtins__ is __builtin__.__dict__


# file2.py
import file1

"""结果:
module name __name__ : file
__builtin__ is __builtins__: False
type(__builtin__): <type 'module'>
type(__builtins__): <type 'dict'>
__builtins__ is __builtin__.__dict__ True
"""


结论:
__builtins__ 是对内建模块  __builtin__ 的引用,并且有如下两个方面差异:

在主模块中,即没有被其他文件导入。__builtins__是对 __builtin__ 本身的引用,两者是相同的。

通过 __builtins__ is __builtin__.__dict__ 猜想:
在非 '__main__' 模块中,也就是模块被导入后,__builtins__ 应该属于 __builtin__.__dict__ 的一部分,是对 __builtin__.__dict__ 的引用,而非builtin本身,它在任何地方都可见,此时builtins的类型是字典。

装饰内建函数
Python 官方文档 解释了如何装饰一个内建函数:

import __builtin__

def open(path):
  f = __builtin__.open(path, 'r')
  return UpperCaser(f)

class UpperCaser:
  __metaclass__ = type

  def __init__(self, f):
    self._f = f

  def read(self):
    return self._f.read().upper()

print open('./a.txt').read()
# 将会全部转为大写输出

Note:Python3.X版本中,内建模块更名为builtins,与Python2.X有所不同

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

您如何在python列表中訪問元素?您如何在python列表中訪問元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具