python 反射

  反射:讓對象告訴咱們他是什麼,他有什麼,並獲取使用
html

本文主要介紹 inspect 模塊的使用:python

inspect模塊: 用於收集python對象的信息,能夠獲取類或函數的參數的信息,源碼,解析堆棧,對對象進行類型檢查等等;app

Doc:這樣寫到ide

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.函數

這個模塊是針對模塊,類,方法,功能等對象提供些有用的方法。spa

  • getmembers(object[, predicate]): 

  這個方法是dir()的擴展版,它會將dir()找到的名字對應的屬性一併返回,形如[(name, value), ...]。另外,predicate是一個方法的引用,若是指定,則應當接受value做爲參數並返回一個布爾值,若是爲False,相應的屬性將不會返回。使用is*做爲第二個參數能夠過濾出指定類型的屬性。code

 

如下例子中展現瞭如何獲取模塊中的類,如何獲取類中的方法:orm

import inspect
import importlib

# 導入模塊
module = importlib.import_module(moduleName)

# 獲取模塊中的全部類
classes = inspect.getmembers(module,inspect.isclass)
 # 遍歷類並過濾
for name, cls in classes:
    if issubclass(cls, TestCase):
        # 獲取類中的方法
        methods = inspect.getmembers(cls,inspect.ismethod)
        for name, method in methods:
            if method.__name__.startswith("test"):
                dict = {
                    'psoName': psoName,
                    'className': module.__name__+"."+cls.__name__,
                    'methodName': method.__name__,
                    'description': method.__doc__
                 }
                 dict['name'] = dict['psoName']+"."+dict['className']+"."+dict['methodName']    

inspect模塊的實現本質是依賴於dir與getattr:htm

def getmembers(object, predicate=None):
    """Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate."""
    results = []
    for key in dir(object):
        try:
            value = getattr(object, key)
        except AttributeError:
            continue
        if not predicate or predicate(value):
       # 元組列表  results.append((key, value)) results.sort()
return results

 反射詳細參考:https://www.cnblogs.com/huxi/archive/2011/01/02/1924317.html對象

相關文章
相關標籤/搜索