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
saximi
V2EX  ›  Python

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

  •  
  •   saximi · 2017-07-26 20:29:04 +08:00 · 1896 次点击
    这是一个创建于 2465 天前的主题,其中的信息可能已经有所发展或是发生改变。
    第一段代码
    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 条回复    2017-07-27 18:39:40 +08:00
    raptium
        1
    raptium  
       2017-07-26 20:42:34 +08:00 via iPhone
    不要把一个 mutable 的对象作为参数默认值
    Readme16
        2
    Readme16  
       2017-07-26 21:19:25 +08:00
    sagaxu
        3
    sagaxu  
       2017-07-26 21:24:04 +08:00 via Android
    @raptium 除非是想曲线救国获得 static 变量
    lxy
        4
    lxy  
       2017-07-26 21:44:14 +08:00
    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  
       2017-07-26 23:54:00 +08:00
    感觉学到了一点黑科技
    NoAnyLove
        6
    NoAnyLove  
       2017-07-27 00:19:48 +08:00
    这是一个经典错误,很多靠谱的 Python 书上都会讲解这个问题
    nongmei
        7
    nongmei  
       2017-07-27 10:42:26 +08:00
    可变对象和不可变对象的区别
    zhusimaji
        8
    zhusimaji  
       2017-07-27 18:37:26 +08:00 via iPhone
    千万不要把可变对象放在参数中
    zhusimaji
        9
    zhusimaji  
       2017-07-27 18:39:40 +08:00 via iPhone
    @zhusimaji 少加了两个字 默认
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5563 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:33 · PVG 11:33 · LAX 20:33 · JFK 23:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.