## Python函数默认参数的一个小陷阱

def foo(a1, args = []):
print "args before = %s" % (args)
args.insert(0, 10)
args.insert(0, 99999)
print "args = %s " % (args)

def main():
foo('a')
foo('b')

if __name__ == "__main__":
main()


args before = []
args = [99999, 10]
args before = [99999, 10]
args = [99999, 10, 99999, 10]


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, e.g.:

def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = []
penguin.append("property of the zoo")
return penguin


• http://simple-is-better.com/ python.cn(news, jobs)

已推荐至：http://simple-is-better.com/news/381