Python is a dynamic language and does not specify a variable type when defining a variable, and the variable type is determined by the value of the variable during code execution. The variable types commonly used in Python have an int float long bool str list tuple set dict and so on, commonly used variable types have types libraries and built -in Type (object) and isinstance (Object,class-or-type-or-tuple) methods, see below for a look at how these methods are used to determine the variable type.
1. Use the types library to combine type (object):
There is a built-in library types in Python that has a series of type constants, such as types. Inttype is of type int, types. StringType is a str type and can be used to determine the variable type by comparing it with the built-in type (object) function:
Import Typesmyint = 1myFloat = 1.1myLong = 11111111111myBool = Truemystr = "teststring" myList = [1, 2]mytuple = (1, 2) Myse t = set ([1, 2]) mydict = {"Name": "Lucy", "Sex": "Female"}# detection type (MYINT) is types. Inttypetype (myfloat) is types. Floattypetype (MyLong) is types. Longtypetype (Mybool) is types. Booleantypetype (MYSTR) is types. StringType (myList) is types. Listtypetype (mytuple) is types. tupletype# The types library does not have a corresponding set type, set can be determined by the following method of type (MYDICT) is types. Dicttype
2. use type (object):
For convenience, you can also use the built-in type (object) method to compare a variable data type directly to a known data type without resorting to the types package:
Type (MYINT) is a type (1) type (myfloat) is a type (. 1) type (MyLong) is a type (1111111111111) type (Mybool) is type (True) type (mystr is the type ("a") type (myList) is the type ([1]) type (mytuple) is type ((1,)) of type (MySet) is type (set ([1])) type (mydict) is type ({1:2 })
3. using isinstance (object, Class-or-type-or-tuple):
The built-in Isinstance (object, Class-or-type-or-tuple) can also be used to determine the variable type and return a Boolean value:
Isinstance (myInt, int) isinstance (myfloat, float) isinstance (mylong, float) isinstance (mybool, BOOL) isinstance (MYSTR, STR) isinstance (myList, list) isinstance (mytuple, tuple) isinstance (MySet, set) isinstance (Mydict, Dict) # The second parameter uses a tuple type isinstance (mydict, (list, tuple, set, dict))
Finish.
This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1682216
First glimpse of Python (four)--three ways to determine the Python variable type