zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    大四实习几个课题
    Keil 4 与Proteus 7.8联调
    局域网共享
    win 8.1 网卡
    路由器无线桥接 router wireless bridge
    系统对话框alert-prompt-confirm
    处理浏览器兼容性
    pageX--clientX--scrollLeft-clientLeft-offsetWidth
    处理注册事件的兼容性问题
    处理innerText的兼容性问题
  • 原文地址:https://www.cnblogs.com/liuzhipenglove/p/7027809.html
Copyright © 2011-2022 走看看