O módulo inspecionar de reflexão python

Adquira o hábito de escrever juntos! Este é o sexto dia da minha participação no "Nuggets Daily New Plan · April Update Challenge", clique para ver os detalhes do evento .

O módulo de inspeção fornece uma série de funções para operações de introspecção. Será descrito a seguir.

As classes e funções envolvidas são as seguintes:

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 Verifique o tipo de objeto

1.1 é o método da série

método ilustrar
ismódulo Verifique se o objeto é um módulo
é classe Verificar se um objeto é uma classe
estáfuncionando Verificar se um objeto é uma função
émétodo Verificar se um objeto é um método
está embutido Verifique se um objeto é uma função ou método interno

por exemplo:

image-20220114111532345.png

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 rotina

Verifique se o objeto é um tipo que pode ser chamado, como uma função, método, função interna ou método, que é exatamente o mesmo que a série is

if inspect.isroutine(p.say):
    p.say()
复制代码

resultado:

小明在谈话
复制代码

1.3 Determinando se um objeto pode ser chamado

Se você apenas julgar se o objeto pode ser chamado, você pode usar um método de julgamento mais simples

from collections.abc import Callable


print(isinstance(p.say, Callable))
复制代码

resultado:

True
复制代码

2 Obter informações do objeto

2.1 método getmembers

Este método é uma versão estendida do 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

O nome do módulo do módulo onde a classe está localizada Ao contrário do método do módulo , o nome do módulo retornado aqui é um objeto que pode ser chamado diretamente em vez de uma string.

print(inspect.getmodule(p.say))
复制代码

resultado:

<module '__main__' from 'D:/workspace/test_study/test_study/test.py'>
复制代码

2.3 método getfile

Obtenha o nome do arquivo definido pelo objeto

print(inspect.getfile(p.say))
复制代码

resultado:

D:/workspace/test_study/test_study/test.py
复制代码

2.4 método getsource

Obter o código-fonte de um objeto

print(inspect.getsource(p.say))
复制代码

resultado:

def say(self):
    print(f"{self.name}在谈话")
复制代码

2.5 método getfullargspec

Obtenha os parâmetros declarados quando o método é definido e o resultado é uma tupla, que são (lista de nomes de parâmetros normais, *nome do parâmetro, **nome do parâmetro, tupla de valor padrão)

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

Usado apenas para stack frame, obtém o valor do parâmetro da chamada de função atual no stack frame, o resultado é uma tupla, respectivamente (lista de nomes de parâmetros normais, *nome do parâmetro, **nome do parâmetro, stack locals())

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,男
复制代码

\

Acho que você gosta

Origin juejin.im/post/7084027275519197197
Recomendado
Clasificación