Python如何检查变量的类型

时间:2018-02-27 14:24:10

标签: python

基本上,我需要检查变量存储的数据类型,然后用新数据替换变量中存储的数据。例如,如何检查变量是否存储字符串数据或整数数据?

源代码:

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

基本上,我应该怎么做,或者有没有传统方法来检查变量存储的数据类型?

4 个答案:

答案 0 :(得分:5)

正确的方法是isinstance

if isinstance(variable, MyClass)

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

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

答案 1 :(得分:0)

如果您真的想要变量的类型,并且不想支持继承,请使用内置的type函数:

if type(variable) is MyClass:
    ...

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

答案 2 :(得分:0)

stats返回变量的类型

答案 3 :(得分:0)

type(variable_name)

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