我知道我可以使用 locals()
或 globals()
来获取 Python 脚本环境中使用的所有本地或全局变量,但 Python 确实如此吗?有一个关键字可以用来仅调用函数内的变量吗?
例如:
def function():
a = 3;
b = 4;
c = float(b+a)
>> keyword(function())
>> [a : <class 'int'>, b : <class 'int'>, c : <class 'float'>]
最佳答案
您是否正在寻找这样的东西:
# define these outside the scope of the function
x = 10
y = 20
def function():
a = 3;
b = 4;
c = float(b+a)
l = locals()
print(", ".join(["{var}: {type}".format(var=v, type=type(l[v])) for v in l]))
function()
#a: <type 'int'>, c: <type 'float'>, b: <type 'int'>
关于python - 如何打印函数内的所有变量及其类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49240964/