[python 函数学习篇]默认参数

python函数:
默认参数: retries=4 这种形式
    def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
        while True:
            ok = raw_input(prompt)
            if ok in ('y', 'ye', 'yes'):
                return True
            if ok in ('n', 'no', 'nop', 'nope'):
                return False
            retries = retries - 1
            if retries < 0:
                raise IOError('refusenik user')
            print complaint

调用的时候:
    只给出必要的参数: ask_ok('Do you really want to quit?')
    给出一个可选的参数: ask_ok('OK to overwrite the file?', 2)
    或者给出所有的参数: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

默认参数的特点:
    重要警告: 默认值只被赋值一次。这使得当默认值是可变对象时会有所不同,比如列表、字典或者大多数类的实例。
    例如,下面的函数在后续调用过程中会累积(前面)传给它的参数:
    

    def f(a, L=[]):
        L.append(a)
        return L

    print f(1)
    print f(2)
    print f(3)
    这将会打印:

    [1]
    [1, 2]
    [1, 2, 3]
    如果你不想在随后的调用中共享默认值,可以像这样写函数:

    def f(a, L=None):
        if L is None:
            L = []
        L.append(a)
        return L

学习网址:

http://docs.pythontab.com/python/python3.4/introduction.html#tut-numbers

posted @ 2017-06-16 15:35  liuzhipenglove  阅读(410)  评论(0编辑  收藏  举报