Python 中的内省

2024 年 8 月 29 日 | 5 分钟阅读

在本教程中,我们将学习 Python 编程语言最强大的功能之一——自省。让我们简要介绍一下自省。

什么是自省?

自省是一种在运行时确定对象类型的方法。我们知道,Python 中的一切都是对象,并且对各种自省方法有广泛的支持。自省是指检查内存中的其他模块和函数作为对象,获取有关它们的信息并进行操作的代码。它提供了熟悉对象属性和特性的便利。通过使用自省,我们可以动态地检查 Python 对象。

Python 是一种动态的、面向对象的、支持自省的语言,其影响力广泛而深入。自省功能使其成为比其他语言更强大的语言。

Python 提供了许多用于代码自省的函数和实用工具。我们还可以定义没有名称的调用函数和引用函数。

dir() 函数

dir() 函数返回对象所属属性和方法的排序列表。让我们通过以下示例来理解,该示例使用 **dir()** 函数返回给定程序中所有可用方法的名称。

示例 -

输出

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

dir() 函数返回列表对象使用的所有方法和属性。

示例 - 2

输出

The methods and attributes are used with integer: 
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
The methods and attributes are used with string: 
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Python type() 函数

type() 函数返回对象的类型。让我们通过以下示例来理解。

示例 -

输出

<class 'int'>
<class 'str'>

示例 - 2

输出

<class 'int'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
<class 'type'>
<class 'function'>
<class 'type'>
<class '__main__.MyClass'>
<class 'module'>

Python hasattr() 函数

hasattr() 函数检查对象是否具有某个属性。根据结果,如果对象具有给定属性,它将返回 True 或 False。让我们通过以下示例来理解。

示例 -

输出

True
False

Python id() 函数

id() 函数返回对象的特殊 ID。让我们通过以下示例来理解。

示例 -

输出

The integer id is:  140736928548512
The string id is:  2423227163376
The list id is:  2423232862400
The set id is:  2423232820480
The list id is:  2423226957888
The object id is:  140736928328528
The functio id is:  2423231111520
The MyClass id is:  2423225796064
The obj id is:  2423232892640
The sys module id is:  2423227235840

Python sys 模块

sys 模块允许我们与解释器使用或维护的系统特定变量和函数进行交互,并与解释器进行强交互的函数。让我们通过以下示例来理解。

示例 -

输出

3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)]
win32
['d:\\Python Project', 'D:\\python_project\\Myfirstdjangoproject\\Hello', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38\\python38.zip', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38\\DLLs', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38\\lib', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38', 'C:\\Users\\User\\.virtualenvs\\Django-ExvyqL3O', 'C:\\Users\\User\\.virtualenvs\\Django-ExvyqL3O\\lib\\site-packages']

在上面的代码中,我们检查了 Python 版本、平台和搜索路径位置。

其他自省方法

还有一些其他重要的自省方法,如下所示。

  • vars() - 它包含所有实例变量(名称和值)作为字典。它等同于 mycar.__dict__.*
  • isinstance() - 它检查一个对象是否是指定的类。
  • getsizeof() - 它是 sys 模块的一部分;它包含对象的大小(以字节为单位)。
  • help() - 它根据文档字符串获取有关对象接口的帮助。
  • callable() - 它检查对象是否可调用。

Python 中的自省属性

我们将讨论一些提供对象有用信息的属性。让我们看一些重要的自省属性。

  • __name__ - 它显示类、函数或方法的原始名称。
  • __qualname__ - 类函数或方法的限定名称。在类/函数/方法定义嵌套的情况下,它经常很有用。
  • __doc__ - 这是一个文档字符串,也可以通过调用内置函数 **help()** 来检索
  • __self__ - 它是方法所属的实例。

结论

我们已经讨论了自省是什么以及它为什么重要。我们已经看到了一些重要的方法和示例。要了解更多关于自省的信息,您可以查看 Python inspect 模块。