Python不同形式的入参,统一形式,判断是否是等效入参的方法
针对相同的函数对象,python有不同的入参形式,实际传递给函数的入参是相同的。
在避免重复调用,对象重复创建时,首先需要确认传入的参数是等效的。
1 import inspect 2 class Demo: 3 def __init__(self, a, b=2, *args, c, d=1, e, f=0, **kwargs): 4 return 100 5 if __name__ == "__main__": 6 func = getattr(Demo, "__init__") 7 sig = inspect.signature(func) 8 x = sig.bind(None, 1, 2, e=1, c=100, f=0) 9 x.apply_defaults() 10 y = sig.bind(None, a=1, b=2, c=100, e=1, ) 11 y.apply_defaults() 12 z = sig.bind(None, 1, c=100, e=1) 13 z.apply_defaults() 14 print(y.arguments == x.arguments == z.arguments) 15 print(x.arguments) 16 17 print(inspect.getcallargs(func, None, 1, 2, e=1, c=100, f=0)) 18 print(inspect.getcallargs(func, None, a=1, b=2, c=100, e=1)) 19 print(inspect.getcallargs(func, None, 1, c=100, e=1))
结果:(windows 10, python3.8环境下)
True
OrderedDict([('self', None), ('a', 1), ('b', 2), ('args', ()), ('c', 100), ('d', 1), ('e', 1), ('f', 0), ('kwargs', {})])
{'self': None, 'a': 1, 'b': 2, 'args': (), 'kwargs': {}, 'e': 1, 'c': 100, 'f': 0, 'd': 1}
{'self': None, 'args': (), 'kwargs': {}, 'a': 1, 'b': 2, 'c': 100, 'e': 1, 'd': 1, 'f': 0}
{'self': None, 'a': 1, 'args': (), 'kwargs': {}, 'c': 100, 'e': 1, 'b': 2, 'd': 1, 'f': 0}
备注:
Signature和getcallargs都能够统一参数的实际入参,但getcallargs返回结果并不统一。
并且getcallargs在Python3.5已经标记为Deprecated。推荐使用第一种方式。

浙公网安备 33010602011771号