class_inspect_example.py
· 529 B · Python
Brut
import inspect
class SampleClass:
"""這是一個示範類別"""
def method_one(self):
"""方法一"""
pass
def method_two(self, x: int) -> str:
"""方法二,回傳字串"""
return str(x)
# 獲取類別的說明
print(f"類別說明: {inspect.getdoc(SampleClass)}")
# 列出類別的所有方法
methods = inspect.getmembers(SampleClass, predicate=inspect.isfunction)
for name, method in methods:
print(f"方法名稱: {name}, 方法簽名: {inspect.signature(method)}")
| 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)}") |
| 20 |
function_inspect_example.py
· 477 B · Python
Brut
import inspect
def example_function(a: int, b: str = "default") -> bool:
"""示範函式,回傳 True 或 False"""
return bool(a)
# 獲取函式參數
signature = inspect.signature(example_function)
print(f"函式簽名: {signature}")
for name, param in signature.parameters.items():
print(f"參數名稱: {name}, 類型: {param.annotation}, 預設值: {param.default}")
# 獲取函式的文件字串
print(f"函式說明: {inspect.getdoc(example_function)}")
| 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)}") |
| 16 |
function_trace_example.py
· 133 B · Python
Brut
import inspect
def trace_function():
print(f"當前執行的函式: {inspect.currentframe().f_code.co_name}")
trace_function()
| 1 | import inspect |
| 2 | |
| 3 | def trace_function(): |
| 4 | print(f"當前執行的函式: {inspect.currentframe().f_code.co_name}") |
| 5 | |
| 6 | trace_function() |
| 7 |