【问题标题】:How do I know what type my variable is?我怎么知道我的变量是什么类型?
【发布时间】:2014-11-25 13:35:33
【问题描述】:

我在阅读 Python 代码时不知道如何确定给定变量的类型。我想知道变量的类型,而无需深入了解为它们初始化值的方法。说,我有一段代码:

import numpy as np

np.random.seed(0)
n = 10000
x = np.random.standard_normal(n)
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
xmin = x.min()
xmax = x.max()
ymin = y.min()
ymax = y.max()

我怎么知道x 是什么类型?在 Java 中,这很简单。就算不知道方法,我也知道变量类型。

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    您可以使用内置的type 函数来检查变量的类型。

    import numpy as np
    
    np.random.seed(0)
    n = 10000
    x = np.random.standard_normal(n)
    print(type(x))
    # numpy.ndarray
    

    如果在 numpy 的特定情况下,您想检查元素的类型,那么您可以这样做

    print(x.dtype)
    # dtype('float64')
    

    【讨论】:

      【解决方案2】:

      Python 是一种dynamically typed 语言。从技术上讲,阅读代码时,如果不跟随代码,或者代码过于简单,您将无法知道变量的类型。

      给你一些报价:

      Python 是强类型的,因为解释器会跟踪所有变量类型。它也非常动态,因为它很少使用它所知道的来限制变量的使用。

      在 Python 中,使用 isinstance() 和 issubclass() 等内置函数来测试变量类型和正确使用是程序的责任。

      您可以使用isinstance(x, type)type(x)在运行时了解变量类型信息。

      【讨论】:

        【解决方案3】:

        使用dtype:

        n = 10000
        x = np.random.standard_normal(n)
        x.dtype
        

        给予:

        dtype('float64')
        

        如果您想了解更多关于array attributes 的详细信息,可以使用info

        np.info(x)
        

        给予:

        class:  ndarray
        shape:  (10000,)
        strides:  (8,)
        itemsize:  8
        aligned:  True
        contiguous:  True
        fortran:  True
        data pointer: 0xba10c48
        byteorder:  little
        byteswap:  False
        type: float64
        

        【讨论】:

          【解决方案4】:

          type(x) 是直截了当的答案。一般不用type来测试输入,而是用isinstance(x, type)来测试。

          【讨论】:

            【解决方案5】:

            在REPL(交互式控制台)中,你也可以这样做

            >>> help(x)
            

            它会显示关于x的类的信息,包括它的方法。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-04-07
              相关资源
              最近更新 更多