python默认参数中的陷阱

来源:平山

在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

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180817G09YP300?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券