*args与**kwargs
在 P y t h o n Python Python中,*args
和**kwargs
通常使用在函数定义里。*args
和**kwargs
都允许用户给函数传不定数量的参数,即使在定义函数的时候不知道调用者会传递几个参数。( *args
和**kwargs
只是一个大家都遵守的习惯,名字可以任意写的。)
*args
能够接收不定量的非关键字参数,会把位置参数转化为 t u p l e tuple tuple。
def func(*args):
for i in args:
print(i)
func(1,2,3,4)
>>>
1
2
3
4
**kwargs
允许传递不定量关键字参数。如果需要在函数中定义不定量个命名参数,那么就要使用**kwargs
,它会把关键字参数转化为 d i c t dict dict。
def func(**kwargs):
for i in kwargs:
print(i,kwargs[i])
func(a=1,b=2,c=3,d=4)
>>>
a 1
b 2
c 3
d 4
关于**kwargs
的TensorFlow
案例
在 T e n s o r F l o w TensorFlow TensorFlow中关于**kwargs
的一个案例:
import tensorflow as tf
tf.keras.layers.ZeroPadding2D(
padding=(1, 1),
data_format=None,
**kwargs
)
调用ZeroPadding2D
时,可以如下传入参数
x = ZeroPadding2D\
(
padding=(1, 1),
name='Conv_padding',
data_format=IMAGE_ORDERING
)(inputs)