来源:python中国网 时间:2019-09-15

  调用函数,每次都传参很麻烦而且有些场景不适用,比如如果我们存储网站用户,有的用户没填写年龄,那么至少给个默认存吧,比如18岁。

  所以,Python允许为参数设置默认值,定义函数时,直接给形式参数指定一个默认值,调用函数时没有给设定默认值的形参传参,则该参数直接使用默认值。

  形参有默认值并不影响调用时给他传参,有传参则实际值为传参值。

	  def 函数名(...,形参名=默认值):

	  代码块


# -*- coding: utf-8 -*-

# 为两个参数指定默认值
def age_info(name, age = 18,site="www.python66.com"):
    print('name',name)
    print("age",age)
    print('站点',site)

age_info('小明')
print('================')
age_info('小明',site = '我爱www.python66.com')
D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
name 小明
age 18
站点 www.python66.com
================
name 小明
age 18
站点 我爱www.python66.com

Process finished with exit code 0



  易错点:

  关键字参数必须位于位置参数的后面,在定义函数时指定了默认值的参数(肯定是关键字参数)必须在没有默认值的参数之后。为了以防万一,可以传参时把参数名写出来。

  错误1:定义函数发生错误

# -*- coding: utf-8 -*-


def age_info(name, age = 18,site):
    print(123)
D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
  File "D:/pyscript/py3script/python66/python66.py", line 5
    def age_info(name, age = 18,site):
                ^
SyntaxError: non-default argument follows default argument

Process finished with exit code 1



  错误2:调用传参错误

# -*- coding: utf-8 -*-


def age_info(name, age = 18,site='www.python66.com'):
    print('name',name)
    print("age",age)
    print('站点',site)

age_info(site = 11,19,age=21)
D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
  File "D:/pyscript/py3script/python66/python66.py", line 10
    age_info(site = 11,19,age=21)
                      ^
SyntaxError: positional argument follows keyword argument

Process finished with exit code 1