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 ofgu s
Without arguments, return the list of scal the cururment, rest 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 implegetment to s__ __getol值: function to function to function to fal. 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 tolduce the mostn lel,objects, as it 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 class object, the list contains the names of its attributes, and class object, the list contains the names of its attributes, and class object. 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.