任意參數*和**的使用

當函數的參數可能爲任意個時,參數列表使用*或者**代替,如

其中*代表列表,**代表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, value2

class 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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章