「Python」Do not use mutable objects as default values in the function or method definition.

昨晚看Google Python Coding style的时候,有一条是这样的:

Do not use mutable objects as default values in the function or method definition.

Yes: def foo(a, b=None):
         if b is None:
             b = []
No:  def foo(a, b=[]):
         ...

这是Python里面一个很奇葩的东西,下面的例子可以说明一切:

>>> def foo(b=[]):
...     b.append(1)
...     return b
... 
>>> foo()
[1]
>>> foo()
[1, 1]
>>> def foo(b=None):
...     if b is None:
...             b=[]
...     b.append(1)
...     return b
... 
>>> foo()
[1]
>>> foo()
[1]

一个语言被设计成这样真是很考验人的说…

想搞清楚这些我提供以下两个参考资料:
http://effbot.org/zone/default-values.htm
http://zephyrfalcon.org/labs/python_pitfalls.html
第二个链接里有更多神奇的内容~

The default argument is bound *once*, when the function is *created*, not when it’s called. (In other words, for a function f(x=[]), x is *not* bound whenever the function is called. x got bound to [] when we defined f, and that’s it.) So if it’s a mutable object, and it has changed, then the next function call will take this same list (which has different contents now) as its default argument.

Everything is object.

Tags : ,

0 thoughts on “「Python」Do not use mutable objects as default values in the function or method definition.”

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Click the right image To submit your comment: