python函式每日一講 - dir()函式

pythontab發表於2014-04-18

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 attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __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__().

The default dir() mechanism behaves differently with different 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.

If 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’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.


相關文章