Function Default Parameters
有关Function的默认参数,会有一些坑,初学时容易中招和疑惑,所以花点时间研究一下,加深印象。
主要是强调默认参数只在定义时初始化赋值一次,特别针对mutable类的默认参数有影响。
Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended.
下面来自培训课上的资料,有关默认参数的基本认知
Default parameters: allow to specify the default values
● they are then optional in the function call
● yet, the function call can override the default values
默认参数是可以选的,并且调用时传入的arguments可以覆盖其值
Default parameters must be declared after non-default parameters
● otherwise, SyntaxError: non default argument follows gets generated;
默认参数必须在非默认参数后
Default parameters are instantiated at the time the function is created:
● namely at function definition time and NOT at function execution time, or runtime;
● The nature of the default parameter instantiation may have adverse affects on the mutable types, e.g., lists and dictionaries used as default parameters to the function
默认参数是在函数定义时就被实例化,并非在执行时。正因为这种特性,mutable默认参数会有负面影响。
还是通过举例来验证吧。
def f(a, L=[]):
print(f'print default parameter L:{L}')
L.append(a)
return L
print(f'print f(1):{f(1)}')
print(f'print f(2):{f(2)}')
print(f'print f(3):{f(3)}')
默认参数初始值为[],随着反复调用,它的值也会变化影响后面的每次调用。
# output:
print default parameter L:[]
print f(1):[1]
print default parameter L:[1]
print f(2):[1, 2]
print default parameter L:[1, 2]
print f(3):[1, 2, 3]
覆盖默认值,这样的结果是我们所期望的。
def f(a, L=[]):
L.append(a)
return L
print(f(1, [1,1]))
print(f(2, [2,2]))
print(f(3, [3,3]))
# output:
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
如果有一定要用默认值,有啥办法能返回我们所期望的结果呢?
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f'print f(1):{f(1)}')
print(f'print f(2):{f(2)}')
print(f'print f(3):{f(3)}')
当使用默认参数时,重新初始化其值
# output:
print f(1):[1]
print f(2):[2]
print f(3):[3]
布置个作业,检验一下你是否真地欣赏到了默认参数的魅力,哈哈!最后输出的结果是?
def make_list(value, default = []):
default.append(value)
return default
def make_another_list(value, default = None):
if default is None:
default = []
default.append(value)
return default
make_list(4)
make_another_list(4)
new_list = make_list('hello') + make_another_list('world')
print(new_list)
推荐阅读
-
php function用法如何递归及return和echo区别
-
vbs(asp)下的Function 语句
-
CSS3 :default伪类选择器使用简介
-
弄了个检测传输的参数是否为数字的Function
-
js init : function ()
-
php判断某个方法是否存在函数function_exists (),method_exists()与is_callable()区别与用法解析
-
asp中去除内容HTML标签的三个function函数
-
js function 返回值的函数(js获取后端方法的返回值)
-
ThinkPHP调用common/common.php函数提示错误function undefined的解决方法
-
php警告Creating default object from empty value 问题的解决方法