【问题标题】:How to print all of the variables and their type inside a function如何在函数中打印所有变量及其类型
【发布时间】:2018-03-13 02:40:38
【问题描述】:

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

【问题讨论】:

  • 无法修改功能吗?
  • “变量及其类型”是什么意思? Python 变量没有 类型,它们可以存储任意对象。如果我做a = 1; a = 2.5; a = 'foo'; a = object()a 的类型会是什么?
  • 是的@Aran-Fey,你是对的。实际上,这应该更多是关于 Keras 的问题,在其中构建已经具有类型(卷积、RNN 等)的神经层,但我也有兴趣以一般方式制作它。

标签: python function variables


【解决方案1】:

您是否正在寻找这样的东西:

# 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'>

【讨论】:

  • 是的@pault,这正是我想要的。谢谢
【解决方案2】:

如果你可以改变函数,你可以返回值然后检查它们的类型。如果你无法修改函数,我认为你不能假设变量类型是什么。

def function():
    a = 3
    b = 4
    c = float(a + b)
    return a, b, c

x, y, z = function()

type(x), type(y), type(z)

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多