首頁  >  文章  >  後端開發  >  python函數之dir()函數

python函數之dir()函數

巴扎黑
巴扎黑原創
2017-08-17 11:03:102476瀏覽

dir()函數

中文說明:

你可以使用內建的dir函數來列出模組定義的識別碼。標識符有函數、類別和變數。

當你為dir()提供一個模組名稱的時候,它會傳回模組定義的名稱清單。如果不提供參數,它會傳回目前模組中定義的名稱清單。

首先,我們來看看在輸入的sys模組上使用dir。我們看到它包含一個龐大的屬性清單。

接下來,我們不給dir函數傳遞參數而使用它-預設地,它會傳回目前模組的屬性清單。注意,輸入的模組同樣是清單的一部分。

為了觀察dir的作用,我們定義一個新的變數a並且給它一個值,然後檢驗dir,我們觀察到在列表中增加了以上相同的值。我們使用del語句刪除目前模組中的變數/屬性,這個變化再一次反映在dir的輸出中。

關於del的一點註解-這個語句在運行後被用來 刪除 一個變數/名稱。在這個例子中,del a,你將無法再使用變數a——它就好像從來沒有存在過一樣。

版本:

各版本都支援函數,python3中仍可用。

程式碼範例:

>>> import struct
>>> dir()   # show the names in the module namespace
['__builtins__', '__doc__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module
['Struct', '__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape(object):
        def __dir__(self):
            return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'perimeter', 'location']

英文說明:

dir([object])

Without arguments, return the list of names in the current local scope . With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attries. that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(),

#If the object does not provide __dir__(), the function insits bitsits the function the sits. __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

irbe#The defchanbe has a custom __getattr__().

irb; types of objects, as it attempts to produce the most relevant, rather than complete, information:

If the object is a module object, the list contains the names of the module's attributes.

I# the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object's attributes'buts, the class' , and recursively of the attributes of its class's base classes.

以上是python函數之dir()函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn