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 []
函数的默认值要注意!!!如果是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 []
相关文章推荐
- python setuptools工具打包
- Python使用QRCode模块生成二维码
- 深入讲解Python编程中的字符串
- windows下用python实现ping
- LeetCode----Power of Two
- Python编程中字符串和列表的基本知识讲解
- python的一道小习题
- python中获得某月有多少天的函数
- python文件操作模块glob
- <LeetCode><Easy>257BinaryTreePaths (深度优先搜索)(列表深拷贝)
- wx.Timer来设置定时事件(绑定定时器)
- python-面向对象(指数对象举例)
- LeetCode----Gray Code
- 【python】通讯录制作
- <LeetCode><Easy>242Valid Anagram (排序)
- 理解 python 装饰器
- python 登录验证
- <LeetCode><Easy>258Add Digits
- <LeetCode><Easy>263 Ugly Number (因式分解)
- python安装-ubuntu之第一篇