Python view data types
In Python, there are several ways to view the data type of an object:
1. Use type()
Use directlytype()
Functions can view the object type:
>>> type(1) <class 'int'> >>> type([]) <class 'list'> >>> type(lambda x: x + 1) <class 'function'>
2. Use isinstance()
isinstance()
You can check whether an object is of a certain type, or a subclass of a certain type:
>>> isinstance(1, int) True >>> isinstance([], list) True >>> isinstance(lambda x: x + 1, function) # function is an alias for typeTrue
3. Check the object's __class__ attribute
Each object has one__class__
The property points to the class that created it:
>>> 1.__class__ <class 'int'> >>> [].__class__ <class 'list'> >>> (lambda x: x + 1).__class__ <class 'function'>
4. Use dir()
We can usedir()
Functions get the list of properties of an object, which usually contains__class__
property:
>>> dir(1) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
You can see,1.__class__
Just in this list.
So Python provides multiple ways to check the type of an object, including:
- type() function
- isinstance() function
-
__class__
property - dir() function
You can select one or more ways to view the object type as needed.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.