¡Acostúmbrate a escribir juntos! Este es el sexto día de mi participación en el "Nuggets Daily New Plan · April Update Challenge", haz clic para ver los detalles del evento .
El módulo de inspección proporciona una serie de funciones para operaciones de introspección. Se describirá a continuación.
Las clases y funciones involucradas son las siguientes:
def test_func(name, age, sex="男", *ids, **info):
"""
返回个人信息
:param name: 姓名
:param age: 年龄
:param sex: 性别
:return: 个人信息
"""
return name + "," + age + "," + sex
class Person(object):
"""
这是一个测试类
"""
def __init__(self, name, age):
self.name = name
self.age = age
def say(self):
print(f"{self.name}在谈话")
p = Person("小明", 23)
复制代码
1 Comprobar el tipo de objeto
1.1 es el método de la serie
método | ilustrar |
---|---|
esmódulo | Comprobar si el objeto es un módulo |
esclase | Comprobar si un objeto es una clase |
es función | Comprobar si un objeto es una función |
esmétodo | Comprobar si un objeto es un método |
está incorporado | Comprobar si un objeto es una función o método incorporado |
p.ej:
import inspect
from test_study import driver_demo
print(inspect.ismodule(driver_demo))
复制代码
resultado:
True
复制代码
print(inspect.isfunction(test_func))
复制代码
resultado:
True
复制代码
print(inspect.isclass(Person))
print(inspect.ismethod(p.say))
复制代码
resultado:
True
True
复制代码
print(inspect.isbuiltin(print))
复制代码
resultado:
True
复制代码
1.2 método de rutina
Compruebe si el objeto es un tipo invocable, como una función, un método, una función integrada o un método, que es exactamente igual que la serie is
if inspect.isroutine(p.say):
p.say()
复制代码
resultado:
小明在谈话
复制代码
1.3 Determinar si un objeto es invocable
Si solo juzga si el objeto es invocable, puede tomar un método de juicio más simple
from collections.abc import Callable
print(isinstance(p.say, Callable))
复制代码
resultado:
True
复制代码
2 Obtener información del objeto
2.1 método getmembers
Este método es una versión extendida del método dir()
print(inspect.getmembers(p.say))
复制代码
resultado:
[('__call__', <method-wrapper '__call__' of method object at 0x0000020F307850C8>), ('__class__', <class 'method'>), ('__delattr__', <method-wrapper '__delattr__' of method object at 0x0000020F307850C8>), ('__dir__', <built-in method __dir__ of method object at 0x0000020F307850C8>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of method object at 0x0000020F307850C8>), ('__format__', <built-in method __format__ of method object at 0x0000020F307850C8>), ('__func__', <function Person.say at 0x0000020F30E8C048>), ('__ge__', <method-wrapper '__ge__' of method object at 0x0000020F307850C8>), ('__get__', <method-wrapper '__get__' of method object at 0x0000020F307850C8>), ('__getattribute__', <method-wrapper '__getattribute__' of method object at 0x0000020F307850C8>), ('__gt__', <method-wrapper '__gt__' of method object at 0x0000020F307850C8>), ('__hash__', <method-wrapper '__hash__' of method object at 0x0000020F307850C8>), ('__init__', <method-wrapper '__init__' of method object at 0x0000020F307850C8>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x00007FFE1190E030>), ('__le__', <method-wrapper '__le__' of method object at 0x0000020F307850C8>), ('__lt__', <method-wrapper '__lt__' of method object at 0x0000020F307850C8>), ('__ne__', <method-wrapper '__ne__' of method object at 0x0000020F307850C8>), ('__new__', <built-in method __new__ of type object at 0x00007FFE1190E030>), ('__reduce__', <built-in method __reduce__ of method object at 0x0000020F307850C8>), ('__reduce_ex__', <built-in method __reduce_ex__ of method object at 0x0000020F307850C8>), ('__repr__', <method-wrapper '__repr__' of method object at 0x0000020F307850C8>), ('__self__', <__main__.Person object at 0x0000020F30E89748>), ('__setattr__', <method-wrapper '__setattr__' of method object at 0x0000020F307850C8>), ('__sizeof__', <built-in method __sizeof__ of method object at 0x0000020F307850C8>), ('__str__', <method-wrapper '__str__' of method object at 0x0000020F307850C8>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x00007FFE1190E030>)]
复制代码
2.2 método getmodule
El nombre del módulo del módulo donde se encuentra la clase. A diferencia del método del módulo , el nombre del módulo devuelto aquí es un objeto al que se puede llamar directamente en lugar de una cadena.
print(inspect.getmodule(p.say))
复制代码
resultado:
<module '__main__' from 'D:/workspace/test_study/test_study/test.py'>
复制代码
2.3 método de obtención de archivos
Obtener el nombre de archivo definido por el objeto
print(inspect.getfile(p.say))
复制代码
resultado:
D:/workspace/test_study/test_study/test.py
复制代码
2.4 método getsource
Obtener el código fuente de un objeto
print(inspect.getsource(p.say))
复制代码
resultado:
def say(self):
print(f"{self.name}在谈话")
复制代码
2.5 método getfullargspec
Obtenga los parámetros declarados cuando se define el método, y el resultado es una tupla, que son (lista de nombres de parámetros normales, *nombre de parámetro, **nombre de parámetro, tupla de valor predeterminado)
print(inspect.getfullargspec(test_func))
复制代码
resultado:
FullArgSpec(args=['name', 'age', 'sex'], varargs='ids', varkw='info', defaults=('男',), kwonlyargs=[], kwonlydefaults=None, annotations={})
复制代码
2.6 Método getargvalues
Solo se usa para el marco de pila, obtenga el valor del parámetro de la llamada de función actual en el marco de pila, el resultado es una tupla, respectivamente (lista de nombres de parámetros normales, * nombre de parámetro, ** nombre de parámetro, locales de pila ())
def test_func(name, age, sex="男", *ids, **info, ):
"""
返回个人信息
:param name: 姓名
:param age: 年龄
:param sex: 性别
:return: 个人信息
"""
print(inspect.getargvalues(inspect.currentframe()))
return name + "," + age + "," + sex
print(test_func("小明", '23'))
复制代码
resultado:
ArgInfo(args=['name', 'age', 'sex'], varargs='ids', keywords='info', locals={'name': '小明', 'age': '23', 'sex': '男', 'ids': (), 'info': {}})
小明,23,男
复制代码
\