是否有任何 Python 对象检查器?

pythonserver side programmingprogramming

在 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 的类型,即高度。

使用 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() 类相关的所有内容。

使用 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() 方法作为对象检查器。


相关文章