任意参数*和**的使用

来源:互联网 发布:遥感数据预处理 编辑:程序博客网 时间:2024/05/17 04:23

当函数的参数可能为任意个时,参数列表使用*或者**代替,如

其中*代表列表,**代表dictionary,访问的方式同列表和dictionary

def write_multiple_items(file, separator, *args):    file.write(separator.join(args))

除了作为任意参数解析,*和**还有一个作用,就是将数组或列表转换为位置参数,或者关键字参数,如:

>>> range(3, 6)             # normal call with separate arguments[3, 4, 5]>>> args = [3, 6]>>> range(*args)            # call with arguments unpacked from a list[3, 4, 5]

>>> def parrot(voltage, state='a stiff', action='voom'):...     print "-- This parrot wouldn't", action,...     print "if you put", voltage, "volts through it.",...     print "E's", state, "!"...>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}>>> parrot(**d)-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

使用*和**有用的实践

1、子类复用父类的方法,而不用管父类如何实现,即使父类发生变化,也不影响到子类

class Foo(object):    def __init__(self, value1, value2):        # do something with the values        print value1, value2class MyFoo(Foo):    def __init__(self, *args, **kwargs):        # do something else, don't care about the args        print 'myfoo'        super(MyFoo, self).__init__(*args, **kwargs)


参考:

http://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists

http://stackoverflow.com/questions/3394835/args-and-kwargs