Python 有物件檢查器嗎?


在 Python 中,沒有內建函式或普通函式可以充當物件檢查器。但是,我們可以使用 `type()`、`help()`、`dir()`、`vars()` 等函式,或 `inspect` 模組來查詢任何物件的屬性、特性和方法。

此外,我們還有其他函式,如 `id()`、`getattr()`、`hasattr()`、`globals()`、`locals()`、`callable()`,這些函式有助於檢視物件內部以瞭解其屬性和方法。在這裡,我們將使用一些內建函式來檢查物件。在此之前,我們將建立一個簡單的 Python 類及其物件,以便在本文中引用。

以下是定義 Python 類的語法

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54

使用 `type()` 函式作為物件檢查器

在 Python 中,`type()` 是一個內建函式,用於獲取有關物件的型別資訊。

語法

type(object, bases, dict) 

引數

  • object: 必需引數。如果只指定一個引數,則 `type()` 函式返回此物件的型別

返回值

這將返回一個新的型別類,或者本質上是一個元類。

示例

讓我們使用上面的 Height 類來了解 `type()` 函式如何用作檢查器。

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
h = Height(2) # Create an object 
print(type(h))

輸出

<class '__main__.Height'>

當我們為 Height 類建立一個物件 h 時,`type()` 函式描述了物件 h 的型別,即 height。

使用 `help()` 函式作為物件檢查器

`help()` 也是 Python 的內建函式,用於獲取有關物件的幫助資訊。以下是此函式的語法

help(object) 

示例

再次以 Height 類為例,看看 `help()` 函式如何描述物件的詳細資訊。

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
help(Height)

輸出

Help on class Height in module __main__:

class Height(builtins.object)
 |  Height(inches)
 |  
 |  A height class that describes height as inches.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, inches)
 |      Assign the amount of inches to the height object
 |  
 |  tocentimeter(self)
 |      Convert the inches to centimeters.
 |      1 inch = 2.54 centimeter
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:

當我們為 Height 類建立一個物件 h 時,`type()` 函式描述了物件 h 的型別,即 height。在這裡,您可以看到與 Height() 類相關的所有內容。

使用 `dir()` 函式

`dir()` 是一個內建函式,它返回一個列表,其中包含物件的全部屬性,它還將返回包含在 `__dict__` 屬性中的鍵。以下是語法

dir(object)

引數

object: 呼叫給定物件的屬性,這是一個可選引數。

示例

`dir()` 方法返回所有現有屬性的列表。在列表的末尾,我們可以看到我們在類中實現的屬性“tocentimeter”。此外,您還可以看到自動生成的屬性,例如“__class__”、“__delattr__”、“__dict__”等。

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
print(dir(Height))

輸出

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'tocentimeter']

使用 `hasattr()` 函式

`hasattr()` 方法用於檢查物件是否具有特定屬性。以下是語法

hasattr(object, name )

引數

  • Object: 要檢查的物件。

  • name: 它是一個字串,是我們想要檢查的特定屬性的名稱。

  • 如果物件中存在所述屬性,則返回“True”,否則返回“False”。

示例

讓我們來看一個例子

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
h = Height(24)
print(hasattr(h,"tocentimeter"))

輸出

True

同樣,我們可以使用 `getattr()`、`id()` 和 `callable()` 方法作為物件檢查器。

更新於:2023年8月23日

瀏覽量:338

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告