API文档:
locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
Note
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
翻译文档:
描述:
这个方法返回一个字典。该字典中存储局部名字空间(当前函数或是类方法)的变量,包括函数的参数。
例子:
#! /usr/bin/env python
#coding=utf-8
aa='ccc'
class TestC:
b = 'bb'
def f(self,x):
print locals()
def fun(param):
x = 0
print locals()
fun('cc')
t = TestC()
t.f('g')
输出:
{'x': 'g', 'self': <__main__.TestC instance at 0x01AC8AA8>}

本文介绍了Python内置函数locals()的功能及用法。locals()用于获取并返回一个表示当前局部符号表的字典,其中包括函数参数等变量。文章通过实例演示了如何在函数中使用locals()来查看局部变量。

被折叠的 条评论
为什么被折叠?



