Python - 获取当前函数中的所有参数信息(名称和值)
代码
import inspect
import random
class P:
def start(self, p1, p2, p3=None, p4=None):
arg_info = inspect.getargvalues(inspect.currentframe())
kwargs = arg_info.locals # 获取到所有参数
print(kwargs)
del kwargs["self"]
try:
self._start(**kwargs)
except Exception as e:
print("Failed:", e)
def _start(self, p1, p2, p3=None, p4=None):
assert random.randint(1, 10) > 5, "~_~"
print("Success:", [p1, p2, p3, p4])
if __name__ == '__main__':
p = P()
p.start(1, 2)