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-08-23

335 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.