V2EX › Python
django views.py 中, datetime.datetime.now() 作为默认参数时值不会改变
By cheerzeng at 2017 年 2 月 6 日 · 3749 次点击hi , 如题, 不知道这是不是 django 的特性?直接用 python 试了没这效果。
import datetime
def test(a, b=datetime.datetime.now()):
print a
print "b %s" %b
print "c %s" %datetime.datetime.now()
test(2)
输出结果 b 的值不会改变, c 的正常。
14 条回复 • 2017-02-07 20:26:10 +08:00
|
1
111111111111 2017 年 2 月 6 日
In [1]: import datetime
In [2]: def test(a, b=datetime.datetime.now()): ...: print a ...: print "b %s" %b ...: print "c %s" %datetime.datetime.now() ...: In [3]: import time In [4]: for i in range(6): ...: time.sleep( 2) ...: test(i) ...: 0 b 2017-02-06 11:53:42.707000 c 2017-02-06 11:55:00.035000 1 b 2017-02-06 11:53:42.707000 c 2017-02-06 11:55:02.039000 2 b 2017-02-06 11:53:42.707000 c 2017-02-06 11:55:04.044000 3 b 2017-02-06 11:53:42.707000 c 2017-02-06 11:55:06.049000 |
|
2
111111111111 2017 年 2 月 6 日
|
|
3
111111111111 2017 年 2 月 6 日
@111111111111 打开之后搜索“原因解释如下:”
|
|
4
jingniao 2017 年 2 月 6 日
年前刚遇到这个问题,你把括号去掉就好了
|
|
5
pango 2017 年 2 月 6 日
请使用:
b=lambda: datetime.datetime.now() 建议先把书看看好,基础概念弄清楚后可以节省很多时间 |
|
6
eyeKi1l 2017 年 2 月 6 日 via Android
默认参数的默认值何时被计算?
|
|
7
cxh116 2017 年 2 月 6 日
def test(a, b=None)):
if b is None: b = datetime.datetime.now() 易懂的办法 |
|
13
twoyuan 2017 年 2 月 7 日
话说这边使用 lambda 和直接传 b=datetime.datetime.now 一样吧
|
推荐学习书目
› 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