【发布时间】: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