python - 如何打印函数内的所有变量及其类型

标签 python function variables

我知道我可以使用 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/

相关文章:

python - 在 Heroku 应用程序中同时运行 Django 和 Node

sql-server - SSIS - 在变量中捕获 "ExecutionResult"/"Data Code"?

jquery - 将变量与 .insertAfter 一起使用不起作用

用于临时动态修改 dict 的 python 配方

python - 运行setup.py后我可以扔掉源代码吗?

仅当从上下文菜单调用时,Python 脚本才会在 subprocess.run() 调用上执行失败

javascript - Unbreak my code - 如何在 javascript 的另一个函数中使用函数名作为参数

有人可以解释这段代码中的这些行吗?

javascript - 如何连接两个数组并以相同的方式部署它们但使用字符串值?

variables - 如何将多个变量传递给 Angular 2 中的一个组件?