推荐学习书目
› 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
saximi
V2EX  ›  Python

请教一个关于“None”的问题

  •  
  •   saximi · Jul 26, 2017 · 2629 views
    This topic created in 3348 days ago, the information mentioned may be changed or developed.
    第一段代码
    def foo(bar=None):
    print("bar=",bar) #语句 1
    if bar is None:
    bar=[]
    bar.append("baz")
    return bar

    print("1:",foo())
    print("2:",foo())
    输出如下:
    bar= None
    1: ['baz']
    bar= None
    2: ['baz']


    第二段代码
    def foo(bar=[]):
    print("bar=",bar) #语句 2
    bar.append("baz")
    return bar

    print("1:",foo())
    print("2:",foo())

    输出如下:
    bar= []
    1: ['baz']
    bar= ['baz']
    2: ['baz', 'baz']

    我可以理解的是,当默认参数初始值为[]时,每次进入函数体时,bar 值会发生变化。
    但是我不理解的是,为何当默认参数 bar 初始值为 None 时会导致刚进入函数体时的 bar 值始终为 None ? None 这个值具有什么特殊性么?谢谢
    9 replies  •  2017-07-27 18:39:40 +08:00
    raptium
        1
    raptium  
       Jul 26, 2017 via iPhone
    不要把一个 mutable 的对象作为参数默认值
    Readme16
        2
    Readme16  
       Jul 26, 2017
    sagaxu
        3
    sagaxu  
       Jul 26, 2017 via Android
    @raptium 除非是想曲线救国获得 static 变量
    lxy
        4
    lxy  
       Jul 26, 2017
    Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “ pre-computed ” value is used for each call. This is especially important to understand when a default parameter is a mutable object...
    https://docs.python.org/3/reference/compound_stmts.html
    zhanglintc
        5
    zhanglintc  
       Jul 26, 2017
    感觉学到了一点黑科技
    NoAnyLove
        6
    NoAnyLove  
       Jul 27, 2017
    这是一个经典错误,很多靠谱的 Python 书上都会讲解这个问题
    nongmei
        7
    nongmei  
       Jul 27, 2017
    可变对象和不可变对象的区别
    zhusimaji
        8
    zhusimaji  
       Jul 27, 2017 via iPhone
    千万不要把可变对象放在参数中
    zhusimaji
        9
    zhusimaji  
       Jul 27, 2017 via iPhone
    @zhusimaji 少加了两个字 默认
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2657 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 02:36 · PVG 10:36 · LAX 19:36 · JFK 22:36
    ♥ Do have faith in what you're doing.