推荐学习书目
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 · Mar 8, 2015 · 3742 views
    This topic created in 4088 days ago, the information mentioned may be changed or developed.

    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 replies    2015-03-08 23:29:25 +08:00
    jacklong
        1
    jacklong  
    OP
       Mar 8, 2015
    代码粘贴进来空格没了,如何缩进?
    tkliuxing
        2
    tkliuxing  
       Mar 8, 2015
    @jacklong 在这里贴代码一般用gist
    还有,你的主题要表达什么呢?
    dddd
        3
    dddd  
       Mar 8, 2015
    默认参数值是可变对象

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

    看这里……
    http://effbot.org/zone/default-values.htm
    dant
        4
    dant  
       Mar 8, 2015 via iPhone
    默认参数指向的对象在定义函数的时候就创建了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2955 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 15:22 · PVG 23:22 · LAX 08:22 · JFK 11:22
    ♥ Do have faith in what you're doing.