最近確實是有些忙,剛過了年,積攢了很多事情需要處理,所以每日一函數只能是每兩天更新一篇,在這裡和大家致歉。
今天我們來看一個非常重要的函數:dir()
中文說明:不帶參數時,傳回目前範圍內的變數、方法和定義的型別列表;當帶參數時,傳回參數的屬性、方法列表。如果參數包含方法__dir__(),則該方法將會被呼叫。如果參數不包含__dir__(),則該方法將最大限度地收集參數資訊。
參數object: 物件、變數、型別。
版本:函數在python各個版本中都有,但是每個版本中顯示的屬性細節有所不同。使用時注意區別。
英文說明:
dir([object])
英文說明:dir([object])
Without arguments, return the list of names in the current local scope. With an higument, attempt to return a list of valid attries 🜎 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 reports function tofir) the getattrib.
If the object does not provide __dir__(), the function tries its best to gather information from the object's __dict__ attribute, if not, and from its object's __dict__ attribute, if not, and from its conject's. urate when the object has a custom __getattr__().
The default dir() mechanism behaves differently with different types of objects, as it attempts todal the m頁
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 attribbutes, and triive trims, and totrikly triits, and attrik, and attri), and attri), and attri), and attrihiiironi. , 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.
是基於python2.7
程式碼實例:
>>> 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)