Python does not need to specify the specific type when defining a variable. The interpreter will automatically check the type of the variable at runtime and perform implicit type conversion as needed. Because Python is a dynamic language, it is generally not recommended. Type conversion.
For example, when performing a "+" operation, if there are data on both sides of the plus sign, perform an addition operation, if both sides are strings, perform a string concatenation operation, if both sides are lists, perform a merge operation, and even perform complex number operations.
The interpreter will call different internal methods at runtime based on the types of variables on both sides. When the variable types on both sides of the plus sign are not the same, and the type conversion cannot be performed, a TypeError exception will be thrown.
In actual development, in order to improve the robustness of the code, we still need to perform type checking. The first thing that comes to mind for type checking is to use types(), such as using types to determine an int type:
Source Code:
#! /usr/bin/env python2.6
# Author: nock.chen
from types import*
mylist =['nock',100,'100','IT']def delete(mylist, item):iftype(item) is IntType:
mylist.remove(item)delete(mylist,100)print(mylist)
Result:
[' nock','100','IT']
We can find some commonly used types in the types module, and the results shown in 2.6.9:
types.BooleanType #bool type
types.BufferType #buffer type
types.BuiltinFunctionType #Built-in functions, such as len()
types.BuiltinMethodType #Built-in methods refer to methods in the class
types.ClassType #Class type
types.CodeType #Code block type
types.ComplexType #Plural type
types.DictProxyType #Dictionary proxy type
types.DictType #Dictionary type
types.DictionaryType #Dictionary backup type
types.EllipsisType #Ellipsis type
types.FileType #file type
types.FloatType #Floating point type
types.FrameType #Type of frame object
types.FunctionType #Function type
types.GeneratorType #Generator generated by calling generator function-iterator object type
types.GetSetDescriptorType #Use PyGetSetDef(Such as FrameType)The type of object defined in the extension module
types.InstanceType #Instance type
types.IntType #int type
types.LambdaType #lambda type
types.ListType #List type
types.LongType #long type
types.MemberDescriptorType #Object types defined in extension modules, including PyMemberDef, such as datetime.timedelta.days
types.MethodType #Method type
types.ModuleType #module type
types.NoneType #None type
types.NotImplementedType #Types of NotImplemented
types.ObjectType #object type
types.SliceType # slice()Object type returned
types.StringType #String type
types.StringTypes #A sequence containing StringType and UnicodeType to facilitate inspection of any string object.
types.TracebackType #In sys.exc_The type of traceback object found in traceback.
types.TupleType #Tuple type
types.TypeType #Type itself
types.UnboundMethodType #Another name for MethodType
types.UnicodeType #Types of Unicode character strings(For example, u' spam)
types.XRangeType # xrange()Type of range object returned
Official website introduction: https://docs.python.org/2/library/types.html
In the Python3 version, the types
module method has been significantly reduced, as follows:
types.BuiltinFunctionType
types.BuiltinMethodType #Type of built-in function, such as len()Or sys.exit(), And the methods of the built-in classes.(Here, "built-in" means "written in C".)
types.CodeType #By compile()The type of code object returned.
types.DynamicClassAttribute
types.FrameType #The type of frame object, as found in tb. tb_frame if tb is a traceback object.
types.FunctionType
types.GeneratorType #Generator created by generator function-Iterator object type.
types.GetSetDescriptorType #Use PyGetSetDef(Such as FrameType)The type of object defined in the extension module.
types.LambdaType #User-defined functions and function types created by lambda expressions.
types.MappingProxyType
types.MemberDescriptorType
types.MethodType #The method type of the user-defined class instance.
types.ModuleType
types.SimpleNamespace
types.TracebackType #The type of traceback object, such as sys.exc_info()
types.new_class
types.prepare_class
Official website introduction: https://docs.python.org/3/library/types.html#module-types
During the version upgrade from Python2 to Python3 above, the type module methods have been reduced. If you use the type method, there will also be the following problems:
As shown above, the types of i and n are not the same. In fact, UserInt inherits int, so this judgment is problematic. When we expand Python built-in types, the result returned by type is not accurate enough. Up. Let's look at another example:
The type comparison result a and b are the same type, the result is obviously inaccurate. For instances of this classical class, type returns the same result, and this result is not what we want. For the built-in basic types, using tpye to check is no problem, but when applied to other situations, the type becomes unreliable.
At this time, we need to use the built-in function isinstance
for type checking. An example is as follows:
isinstance(object, class_or_type_or_tuple)
Object represents an object, and classinfo can be a direct or indirect class name, basic type, or a tuple composed of them.
nock:ucode nock$ python3
Python 3.5.1(default, Dec 262015,18:08:53)[GCC 4.2.1 Compatible Apple LLVM 7.0.2(clang-700.1.81)] on darwin
Type "help","copyright","credits" or "license"for more information.>>>isinstance(2, float)
False
>>> isinstance(2, int)
True
>>> isinstance((2,3), list)
False
>>> isinstance((2,3), tuple)
True
>>> isinstance({'name':'nock'}, tuple)
False
>>> isinstance({'name':'nock'}, dict)
True
>>> isinstance([1,100,101],(str, list, tuple))
True
>>> isinstance(2**31, dict)
False
>>> isinstance(2**31, long)Traceback(most recent call last):
File "<stdin>", line 1,in<module>
NameError: name 'long' is not defined
>>> isinstance(2**31, int)
True
Python2 has int
and long
types for non-floating point numbers. The maximum value of the int type cannot exceed sys.maxint
, and this maximum value is platform dependent. The long integer type can be defined by appending a L
at the end of the number. Obviously, it has a larger range of numbers than the int type. In Python3, there is only one type of integer type int
. In most cases, it is very similar to the long integer type in Python2. Since there are no two types of integers, there is no need to use a special syntax to distinguish them. Further reading: PEP 237.
Finally, the best way to judge your type in Python is to use the built-in function isinstance
to complete the best experience.
Official website introduction: https://docs.python.org/3/library/functions.html#isinstance
Recommended Posts