簡體   English   中英

Python函數內省:在其中提到了作為參數傳遞的類的成員?

[英]Python function introspection: what members of a class passed as argument are mentioned inside it?

假設我有以下功能:

def eggs(a,b,c):
    if c.foo:
        return a + b.bar
    else:
        return c.spam

我希望有一個更高階的函數能夠內省傳遞的函數,並通過點語法檢索代碼中提到的參數成員,具有以下行為:

>>> member_inspector(eggs, 'c')
('foo','spam')

>>> member_inspector(eggs, 'b')
('bar')

>>> member_inspector(eggs, 'a')
()

可以這樣做嗎? 怎么樣?

這是一個基本版本:

import inspect
from textwrap import dedent
import ast

def member_inspector(f, var):
    source = dedent(inspect.getsource(f))
    module = ast.parse(source)
    func = module.body[0]
    result = []
    for stmt in func.body:
        for node in ast.walk(stmt):
            if (isinstance(node, ast.Attribute) and
                    isinstance(node.value, ast.Name) and
                    node.value.id == var):
                result.append(node.attr)
    return result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM