关于Python函数的默认参数 - nixBlog
Python脚本:sgf2asy.py

关于Python函数的默认参数

nix posted @ 2012年1月19日 21:46 in Python with tags python 函数参数 , 6706 阅读

演示Python的函数参数默认值让人困惑的地方,如下代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 关于函数的默认参数,Block A 和 Block B 有差别吗?
# 从输出来看,是有,但是为什么呢?

def make_node(color='@', children=list()):
	node = {
		'color': color,
		'children': children
	}
	return node

if __name__=='__main__':
	if True: # Block A
		a = make_node(color='#', children=list())
		x = a
		b = make_node(color='$', children=list())
		x['children'].append(b)
		x = b
		c = make_node(color='%', children=list())
		x['children'].append(c)
		print a
		print '---------------------------------------A END\n\n'
	
	if True: # Block B
		a = make_node(color='#')
		x = a
		b = make_node(color='$')
		x['children'].append(b)
		x = b
		c = make_node(color='%')
		x['children'].append(c)
		print a
		print '---------------------------------------B END'

看看输出:

{'color': '#', 'children': [{'color': '$', 'children': [{'color': '%', 'children': []}]}]}
---------------------------------------A END


{'color': '#', 'children': [{'color': '$', 'children': [...]}, {'color': '%', 'children': [...]}]}
---------------------------------------B END

Block A的输出是我要达到的效果。而在Block B里,节点的list是同一个(也就是对象ID一样),这当然是我不希望看到的结果!

那么是什么原因导致我不能少敲些字符呢?关于Python函数的默认参数有什么介绍文档呢?

Avatar_small
nix 说:
2012年1月19日 22:06

Block B里输出的list()是[...],中间有些点点,这应该是个特别的意思。总之在写程序时又得到一点经验,很开心。

yangzhe1990 说:
2012年1月19日 23:16

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 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.

yangzhe1990 说:
2012年1月19日 23:17

...的意思应该是递归了不输出了

Iven 说:
2012年1月20日 09:38

list() 好奇怪的写法……通常不是会写 [] 么……虽然这样写会有同样问题……

Avatar_small
nix 说:
2012年1月20日 11:08

这个主要是为了这个例子里看着清楚一点,常用还是[]

Avatar_small
依云 说:
2012年4月03日 22:40

永远别用 mutable 对象作函数默认参数,除非你有特殊的用途。

seo service london 说:
2024年1月16日 22:09

I am huge fan of guitar and want to learn and apply some tricks to play guitar easily.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter