这两个代码片段之间有什么区别?使用type():
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
Run Code Online (Sandbox Code Playgroud)
使用isinstance():
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
Run Code Online (Sandbox Code Playgroud) 基本上,我需要检查变量存储的数据类型,然后用新数据替换变量中存储的数据.例如,如何检查变量是存储字符串数据还是整数数据?
源代码:
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 …Run Code Online (Sandbox Code Playgroud)