码迷,mamicode.com
首页 > 编程语言 > 详细

python关于函数形参

时间:2018-12-28 15:30:02      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:end   永久   mutable   call   explicit   过程   UNC   ini   数据类型   

1.函数的默认参数是可变数据类型时,要尤其注意:如果函数执行过程中默认参数被修改,则永久被修改(下次调用时还会使用上一次被改过的默认参数)

 

 

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. A way around this is to use None as the default, and explicitly test for it in the body of the function.

 

 

 1 #示例
 2 def whats_on_the_telly(penguin=[]):
 3     l=[1,2,3,4]
 4     penguin.append("property of the zoo")
 5     l.append(666)
 6     return penguin, l
 7 a,c=whats_on_the_telly()
 8 print(a,c)
 9 b,d=whats_on_the_telly()
10 print(b,d)
11 #result
12 [property of the zoo] [1, 2, 3, 4, 666]
13 [property of the zoo, property of the zoo] [1, 2, 3, 4, 666]
14 #解决方案
15 def whats_on_the_telly(penguin=None):#修改为None
16     if penguin is None:  #增加
17         penguin = []      #增加
18     l=[1,2,3,4]
19     penguin.append("property of the zoo")
20     l.append(666)
21     return penguin, l
22 a,c=whats_on_the_telly()
23 print(a,c)
24 b,d=whats_on_the_telly()
25 print(b,d)
26 #result
27 [property of the zoo] [1, 2, 3, 4, 666]
28 [property of the zoo] [1, 2, 3, 4, 666]

 

python关于函数形参

标签:end   永久   mutable   call   explicit   过程   UNC   ini   数据类型   

原文地址:https://www.cnblogs.com/mr-slow/p/10190498.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!