【问题标题】:Python how to check the type of a variablePython如何检查变量的类型
【发布时间】:2018-02-27 22:28:08
【问题描述】:

基本上,在用新数据替换存储在变量中的数据之前,我需要检查变量存储的数据类型。例如,如何判断变量存储的是字符串数据还是整数数据?

源代码:

class Toy:

    #Toy Class Constructor
    def __init__(self):
        Name = "Train Engine";
        ID = "TE11";
        Price = 0.99;
        Minimum_Age = 4;

    #Return Name
    def Return_Name(self):
        print(Name)
        return Name

    #Set Name
    def Set_Name(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        Name = Variable

    #Return ID
    def Return_ID(self):
        print(ID)
        return ID

    #Set ID
    def Set_ID(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        ID = Variable

    #Return Price
    def Return_Price(self):
        print(Price)
        return Price

    #Set Price
    def Set_Price(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        Price = Variable

    #Return Minimum_Age
    def print_Minimum_Age(self):
        print(Minimum_Age)
        return Minimum_Age

    #Set Minimum_Age
    def Set_Minimum_Age(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        Minimum_Age = Variable

所以基本上,我应该如何,或者是否有任何常规方法来检查变量存储的数据类型?

【问题讨论】:

  • 你可以使用type
  • type(variable_name) 使用它
  • 唯一需要 isinstance() 的情况是在检查给定类与另一个类的继承时,正如您所说和引用的那样。 type() 仅用于检查实例是否完全属于给定的基本类型。感谢@zmo 这是链接stackoverflow.com/questions/21894575/…
  • 这里有一个微妙的区别:变量没有类型,有。

标签: python


【解决方案1】:

正确的做法是isinstance

if isinstance(variable, MyClass)

但如果你真的需要这个,请三思。 Python 使用鸭子类型,因此显式检查类型并不总是一个好主意。如果您仍想这样做,请考虑使用一些 abstract base 或最有价值的类型进行检查。

正如其他人建议的那样,只需通过type(variable) 获取变量的类型,但在大多数情况下最好使用isinstance,因为这将使您的代码多态 - 您将自动支持子类的实例目标类型。

【讨论】:

  • 所以基本上如果我想检查一个字符串的数据类型,那么我会使用 'isinstance(Variable, str)' ?
  • 在 python3 中 - 是的。在 python2 - isinstance(var, basesting) 在大多数情况下 - 使用 str 以及 unicode 操作
  • 谢谢,成功了
【解决方案2】:

如果你真的想要一个变量的类型,又不想支持继承,可以使用内置的type函数:

if type(variable) is MyClass:
    ...

我同意@Slam,您应该负责任地使用它。

【讨论】:

    【解决方案3】:

    type(variable_name)返回变量的类型

    【讨论】:

      【解决方案4】:

      type(variable)

      此命令将返回变量存储的数据类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-12
        • 2018-03-21
        • 1970-01-01
        • 2010-10-02
        • 2021-01-13
        • 2021-11-17
        • 2011-04-28
        • 1970-01-01
        相关资源
        最近更新 更多