Última actividad 9 months ago

inspect 模組允許在執行時動態獲取函式、類別、模組的結構與資訊,適用於 除錯、程式碼分析、自動文件生成、動態調試 等場景。

timmy revisó este gist 9 months ago. Ir a la revisión

3 files changed, 40 insertions

class_inspect_example.py(archivo creado)

@@ -0,0 +1,19 @@
1 + import inspect
2 +
3 + class SampleClass:
4 + """這是一個示範類別"""
5 + def method_one(self):
6 + """方法一"""
7 + pass
8 +
9 + def method_two(self, x: int) -> str:
10 + """方法二,回傳字串"""
11 + return str(x)
12 +
13 + # 獲取類別的說明
14 + print(f"類別說明: {inspect.getdoc(SampleClass)}")
15 +
16 + # 列出類別的所有方法
17 + methods = inspect.getmembers(SampleClass, predicate=inspect.isfunction)
18 + for name, method in methods:
19 + print(f"方法名稱: {name}, 方法簽名: {inspect.signature(method)}")

function_inspect_example.py(archivo creado)

@@ -0,0 +1,15 @@
1 + import inspect
2 +
3 + def example_function(a: int, b: str = "default") -> bool:
4 + """示範函式,回傳 True 或 False"""
5 + return bool(a)
6 +
7 + # 獲取函式參數
8 + signature = inspect.signature(example_function)
9 + print(f"函式簽名: {signature}")
10 +
11 + for name, param in signature.parameters.items():
12 + print(f"參數名稱: {name}, 類型: {param.annotation}, 預設值: {param.default}")
13 +
14 + # 獲取函式的文件字串
15 + print(f"函式說明: {inspect.getdoc(example_function)}")

function_trace_example.py(archivo creado)

@@ -0,0 +1,6 @@
1 + import inspect
2 +
3 + def trace_function():
4 + print(f"當前執行的函式: {inspect.currentframe().f_code.co_name}")
5 +
6 + trace_function()
Siguiente Anterior