Python如何检查变量的类型

Mar*_*arc 0 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
Run Code Online (Sandbox Code Playgroud)

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

Sla*_*lam 5

正确的方法是这样做 isinstance

if isinstance(variable, MyClass)
Run Code Online (Sandbox Code Playgroud)

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

正如其他人所建议的那样,只需要获取变量的类型type(variable),但在大多数情况下,它的使用效果更好isinstance,因为这会使您的代码具有多态性 - 您将自动支持目标类型的子类实例.