python 中参数*args, **kwargs
def foo(*args, **kwargs):
print ‘args = ‘, args
print ‘kwargs = ‘, kwargs
print ‘---------------------------------------‘
if __name__ == ‘__main__‘:
foo(1,2,3,4)
foo(a=1,b=2,c=3)
foo(1,2,3,4, a=1,b=2,c=3)
foo(‘a‘, 1, None, a=1, b=‘2‘, c=3)输出结果如下:
args = (1, 2, 3, 4)
kwargs = {}
args = ()
kwargs = {‘a‘: 1, ‘c‘: 3, ‘b‘: 2}
args = (1, 2, 3, 4)
kwargs = {‘a‘: 1, ‘c‘: 3, ‘b‘: 2}
args = (‘a‘, 1, None)
kwargs = {‘a‘: 1, ‘c‘: 3, ‘b‘: ‘2‘}
可以看到,这两个是Python中的可变参数。*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个 dict。并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前,像foo(a=1, b=‘2‘, c=3,
a‘, 1, None, )这样调用的话,会提示语法错误“SyntaxError: non-keyword arg after keyword arg”。
-------------------------------------------------------------------------------------------这里看下网上github的代码:
def layer(op): ‘‘‘Decorator for composable network layers.‘‘‘ def layer_decorated(self, *args, **kwargs): # Automatically set a name if not provided. name = kwargs.setdefault(‘name‘, self.get_unique_name(op.__name__)) # Figure out the layer inputs. if len(self.terminals) == 0: raise RuntimeError(‘No input variables found for layer %s.‘ % name) elif len(self.terminals) == 1: layer_input = self.terminals[0] else: layer_input = list(self.terminals) # Perform the operation and get the output. layer_output = op(self, layer_input, *args, **kwargs) # Add to layer LUT. self.layers[name] = layer_output # This output is now the input for the next layer. self.feed(layer_output) # Return self for chained calls. return self return layer_decorated 参考:http://blog.csdn.net/anhuidelinger/article/details/10011013 继续
python @ 用法
def funA(arg):
print ‘A‘
a=arg()
@funA
def funB():
print ‘B‘
此处的@相当于funA(funB())
装饰器背后的主要动机源自python面向对象编程,装饰器是在函数调用之上的修饰,这些修饰仅是当声明一个函数或者方法的时候,才会应用的额外调用。
装饰器的语法以@开头,接着是装饰器韩式的名字和可选的参数。紧跟着装饰器声明的是被修饰的函数,和修饰函数的可选参