Python dir() 函式



**Python dir() 函式**列出了指定物件的全部屬性和方法,包括預設屬性。這裡,物件可以是任何模組、函式、字串、列表、字典等。

如果未向**dir()**傳遞任何引數,它將返回當前本地作用域中的名稱列表。當提供引數時,它會返回該物件有效屬性的列表,但不包含值。

**dir()** 函式是內建函式之一,不需要匯入任何模組。

語法

以下是 python **dir()** 函式的語法。

dir(object)

引數

以下是 python **dir()** 函式的引數:

  • **object** - 此引數指定要列出其屬性的物件。

返回值

python **dir()** 函式返回指定物件的屬性列表。

dir() 函式示例

練習以下示例以瞭解 Python 中 **dir()** 函式的使用。

示例:不帶任何引數的 dir() 函式

當我們列印不帶任何引數的 dir() 的值時,我們會獲得作為標準庫一部分可用的方法屬性的列表。

print("dir method without using any arguments")
print(dir())

執行上述程式後,將生成以下輸出:

dir method without using any arguments
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'traceback']

示例:使用使用者定義類的 dir() 函式

如果我們將使用者定義類的物件傳遞給 dir() 函式,它將顯示該物件的屬性和方法。它還包括對該特定物件預設的內建屬性。

class newClass:
   def __init__(self):
      self.x = 55
      self._y = 44

   def newMethod(self):
      pass

newObj = newClass()
print("List of methods and properties of given class:")
print(dir(newObj))

以下是執行上述程式獲得的輸出:

List of methods and properties of given class:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_y', 'newMethod', 'x']

示例:使用 dir() 列印模組的屬性和方法

**dir()** 函式允許我們顯示 Python 內建模組的屬性和方法,如下面的程式碼所示。

import math
print("List of methods and properties of MATH module:")
print(dir(math))

執行上述程式後,將獲得以下輸出:

List of methods and properties of MATH module:
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

示例:檢查父類的繼承方法和屬性

如果我們想檢查父類的繼承方法和屬性,那麼我們可以透過傳遞子類的物件來使用 dir() 函式。

class Pclass:
   def pMethod(self):
      pass
class Chclass(Pclass):
   def chMethod(self):
      pass

chObj = Chclass()
print("List of methods and properties of Parent class:")
print(dir(chObj))

執行上述程式後,將顯示以下輸出:

List of methods and properties of Parent class:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'chMethod', 'pMethod']

python_built_in_functions.htm
廣告