V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
jacklong
V2EX  ›  Python

Error - Default argument is mutable

  •  
  •   jacklong ·
    jack-long · 2015-03-08 21:54:55 +08:00 · 2741 次点击
    这是一个创建于 3342 天前的主题,其中的信息可能已经有所发展或是发生改变。

    import doctest

    def foo(bar=[]):
    """Error: Default argument is mutable.

    Default argument values are evaluated only once at function definition time,
    which means that modifying the default value of the argument will affect
    all subsequent calls of the function.
    
    >>> foo()
    ['baz']
    >>> foo()
    ['baz', 'baz']
    >>> foo()
    ['baz', 'baz', 'baz']
    """
    bar.append("baz")
    print bar
    

    doctest.testmod()

    4 条回复    2015-03-08 23:29:25 +08:00
    jacklong
        1
    jacklong  
    OP
       2015-03-08 21:56:33 +08:00
    代码粘贴进来空格没了,如何缩进?
    tkliuxing
        2
    tkliuxing  
       2015-03-08 22:45:08 +08:00
    @jacklong 在这里贴代码一般用gist
    还有,你的主题要表达什么呢?
    dddd
        3
    dddd  
       2015-03-08 23:23:26 +08:00
    默认参数值是可变对象

    可以这样:
    def foo(bar=None):
    if bar is None:
    bar = []

    看这里……
    http://effbot.org/zone/default-values.htm
    dant
        4
    dant  
       2015-03-08 23:29:25 +08:00 via iPhone
    默认参数指向的对象在定义函数的时候就创建了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2391 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:54 · PVG 20:54 · LAX 05:54 · JFK 08:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.