来源:平山
在python中,函数参数使用默认值时需要注意一个陷阱。举例说明如下:
实例一:
实例二:
[2]
[2, 2]
[Finished in 0.1s]
实例二的输出结果为什么是这样呢?
问题解释:
python的内部机制是这样处理默认参数的,如下:
Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that 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. A way around this is to use None as the default, and explicitly test for it in the body of the function.
看英文可能比较费劲,好吧,中文如下:
python中缺省参数和函数是绑定的。当一个函数有一个默认参数,并且默认参数是空的可变类型时(dict和list),该可变类型只初始化一次,之后的每次操作,都在前一次的操作基础上操作。但是对于默认参数是不可变的类型时(tuple和字符串和数字),不会有这种情况,如实例一所示。
看完本文有收获?请转发分享给更多人
关注 【小蟒社区】,一起学Python
领取专属 10元无门槛券
私享最新 技术干货