python的locals()妙用

2023-07-29,,

如果你是个喜欢偷懒的程序员并想让代码看起来更加简明,可以利用 Python 的内建函数 locals() 。它返回的字典对所有局部
变量的名称与值进行映射。因此,前面的视图可以重写成下面这个样子:
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())

上面的代码等于下面的

def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})

python的locals()妙用的相关教程结束。

《python的locals()妙用.doc》

下载本文的Word格式文档,以方便收藏与打印。