Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Inspect Live Objects ใน Python

โมดูล inspect ให้ข้อมูลเกี่ยวกับ Live Objects: Modules, Classes, Methods, Functions, Code Objects ฯลฯ ทำ Type Checking, ดึง Source Code, ตรวจสอบ Classes/Functions, ตรวจสอบ Interpreter Stack

ฟังก์ชันหลัก

  • getmembers(object, predicate=None): คืนสมาชิกทั้งหมดเป็น List of (name, value) เรียงตามชื่อ ถ้ามี predicate จะกรองเฉพาะที่ True
  • getmodulename(path): คืนชื่อโมดูลจาก File Path (ไม่รวม Package names)

ไฟล์ตัวอย่าง (inspect_example.py)


'''This is module docstring'''
def hello():
    '''hello docstring'''
    print('Hello world')
    return

class parent:
    '''parent docstring'''
    def __init__(self):
        self.var = 'hello'
    def hello(self):
        print(self.var)

class child(parent):
    def hello(self):
        '''hello function overridden'''
        super().hello()
        print("How are you?")

การใช้งาน getmembers()


>>> import inspect, inspect_example
>>> for k, v in inspect.getmembers(inspect_example):
...     if not k.startswith('__'):
...         print(k, v)
child 
hello 
parent 

Predicates (เงื่อนไขกรอง)

Predicateคำอธิบาย
ismodule()True ถ้าเป็น Module
isclass()True ถ้าเป็น Class
ismethod()True ถ้าเป็น Bound Method
isfunction()True ถ้าเป็น Function (รวม Lambda)
isgenerator()True ถ้าเป็น Generator
iscode()True ถ้าเป็น Code Object
isbuiltin()True ถ้าเป็น Built-in Function/Method
isabstract()True ถ้าเป็น Abstract Base Class

กรองเฉพาะ Classes


>>> for k, v in inspect.getmembers(inspect_example, inspect.isclass):
...     print(k, v)
child 
parent 

ดึงข้อมูล Class/Function


>>> inspect.getmembers(inspect_example.child)
# สมาชิกทั้งหมดของ class child

>>> x = inspect_example.child()
>>> inspect.getmembers(x)
# Instance attributes/methods

ดึง Docstring และ Source Code


>>> inspect.getdoc(inspect_example)
'This is module docstring'
>>> inspect.getdoc(inspect_example.parent)
'parent docstring'
>>> inspect.getdoc(inspect_example.hello)
'hello docstring'

>>> print(inspect.getsource(inspect_example.hello))
def hello():
    '''hello docstring'''
    print('Hello world')
    return

>>> sign = inspect.signature(inspect_example.parent.hello)
>>> print(sign)
(self)

Command Line Interface


$ python -m inspect -d inspect_example
Target: inspect_example
Origin: C:\python36\inspect_example.py
Cached: C:\python36\__pycache__\inspect_example.cpython-36.pyc
Loader: 

$ python -m inspect inspect_example:hello
def hello():
    '''hello docstring'''
    print('Hello world')
    return

ประโยชน์การใช้งาน

  • Debugging และ Introspection
  • สร้าง Documentation อัตโนมัติ
  • Testing Framework (ค้นหา Test Methods)
  • Plugin Systems (ค้นหา Classes/Functions ที่ลงทะเบียน)
  • Serialization/Deserialization (ดู Signature/Annotations)