Pythonリフレクションの検査モジュール

一緒に書く習慣をつけましょう!「ナゲッツデイリーニュープラン・4月アップデートチャレンジ」に参加して6日目です。クリックしてイベントの詳細をご覧ください

inspectモジュールは、イントロスペクション操作のための一連の機能を提供します。以下に説明する。

関連するクラスと関数は次のとおりです。

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オブジェクトタイプを確認します

1.1は直列方式です

方法 説明する
ismodule オブジェクトがモジュールかどうかを確認します
isclass オブジェクトがクラスであるかどうかを確認します
isfunction オブジェクトが関数であるかどうかを確認します
ismethod オブジェクトがメソッドであるかどうかを確認します
isbuiltin オブジェクトが組み込みの関数またはメソッドであるかどうかを確認します

例えば:

image-20220114111532345.png

import inspect
from test_study import driver_demo
​
print(inspect.ismodule(driver_demo))
复制代码

結果:

True
复制代码
print(inspect.isfunction(test_func))
复制代码

結果:

True
复制代码
print(inspect.isclass(Person))
print(inspect.ismethod(p.say))
复制代码

結果:

True
True
复制代码
print(inspect.isbuiltin(print))
复制代码

結果:

True
复制代码

1.2isroutineメソッド

オブジェクトが関数、メソッド、組み込み関数、メソッドなどの呼び出し可能な型であるかどうかを確認します。これは、isシリーズとまったく同じです。

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

結果:

小明在谈话
复制代码

1.3オブジェクトが呼び出し可能かどうかの判断

オブジェクトが呼び出し可能かどうかを判断するだけの場合は、より簡単な判断方法を使用できます

from collections.abc import Callable


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

結果:

True
复制代码

2オブジェクト情報を取得する

2.1getmembersメソッド

このメソッドは、dir()メソッドの拡張バージョンです。

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

結果:

[('__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.2getmoduleメソッド

クラスが配置されているモジュールのモジュール名。moduleメソッドとは異なり、ここで返されるモジュール名は、文字列の代わりに直接呼び出すことができるオブジェクトです。

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

結果:

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

2.3getfileメソッド

オブジェクトによって定義されたファイル名を取得します

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

結果:

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

2.4getsourceメソッド

オブジェクトのソースコードを取得する

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

結果:

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

2.5getfullargspecメソッド

メソッドが定義されたときに宣言されたパラメーターを取得すると、結果はタプルになります。これは、(通常のパラメーター名リスト、*パラメーター名、**パラメーター名、デフォルト値のタプル)です。

print(inspect.getfullargspec(test_func))
复制代码

結果:

FullArgSpec(args=['name', 'age', 'sex'], varargs='ids', varkw='info', defaults=('男',), kwonlyargs=[], kwonlydefaults=None, annotations={})
复制代码

2.6getargvaluesメソッド

スタックフレームにのみ使用され、スタックフレームで現在の関数呼び出しのパラメーター値を取得します。結果はそれぞれタプルになります(通常のパラメーター名リスト、*パラメーター名、**パラメーター名、スタック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'))
复制代码

結果:

ArgInfo(args=['name', 'age', 'sex'], varargs='ids', keywords='info', locals={'name': '小明', 'age': '23', 'sex': '男', 'ids': (), 'info': {}})
小明,23,男
复制代码

\

おすすめ

転載: juejin.im/post/7084027275519197197