推荐学习书目
› 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 · 4216 views
    This topic created in 4262 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
    jacklong
    OP
    Mar 8, 2015
    1
    代码粘贴进来空格没了,如何缩进?
    tkliuxing
    tkliuxing
    Mar 8, 2015
    2
    @jacklong 在这里贴代码一般用gist
    还有,你的主题要表达什么呢?
    dddd
    dddd
    Mar 8, 2015
    3
    默认参数值是可变对象

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

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