您的位置:首页 > 编程语言 > Python开发

python 函数中或者new一个对象的时候 默认值如果设为list, dict, or sets要注意

2015-10-14 17:11 676 查看
ref:http://docs.python-guide.org/en/latest/writing/gotchas/

函数的默认值要注意!!!如果是list, dict ,sets 给默认值得时候 不要在arguments 里面给,要在函数内部给

example

class T:

def __init__(self, a1 = []):

self.a1 = a1

如果这样写

t = T()这个时候 t.a1 是[], 但是如果 update了 t.a1之后,再次 new一个对象 t1 = T(), 这个时候 t1.a1 就不是空list,就跟t.a1一样。

所以要修改成

class T:

def __init__(self, a1 = None):

self.a1 = a1 or []
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: