There are two type judgment functions in Python, type() and isinstance().
Use type()
First, we determine the object type and use the type() function:
Basic types can be judged by type():
>>> type(123) <type 'int'> >>> type('str') <type 'str'> >>> type(None) <type 'NoneType'>
If a variable points to a function or class, it can also be judged by type():
>>> type(abs) <type 'builtin_function_or_method'> >>> type(a) <class '__main__.Animal'>
But what does the type() function return? What about type? It returns type type.
Using isinstance()
For class inheritance relationships, it is very inconvenient to use type(). To determine the type of class, we can use the isinstance() function.
Let’s review the last example. If the inheritance relationship is:
object -> Animal -> Dog -> Husky
Then, isinstance() can tell us whether an object is of a certain type. First create three types of objects:
>>> a = Animal() >>> d = Dog() >>> h = Husky()
Then, judge:
>>> isinstance(h, Husky) True
There is no problem, because the h variable points to the Husky object.
Rejudgment:
>>> isinstance(h, Dog) True
Although h itself is of Husky type, since Husky is inherited from Dog, h is also of Dog type. In other words, isinstance() determines whether an object is of the type itself, or is on the parent inheritance chain of the type.
Therefore, we can be sure that h is still an Animal type:
>>> isinstance(h, Animal) True
Similarly, d whose actual type is Dog is also an Animal type:
>>> isinstance(d, Dog) and isinstance(d, Animal) True
However, d is not a Husky type :
>>> isinstance(d, Husky) False
The basic type that can be judged by type() can also be judged by isinstance():
>>> isinstance('a', str) True >>> isinstance(u'a', unicode) True >>> isinstance('a', unicode) False
And it can also be judged whether a variable is one of certain types, such as the following You can use the code to determine whether it is str or unicode:
>>> isinstance('a', (str, unicode)) True >>> isinstance(u'a', (str, unicode)) True
Since both str and unicode are inherited from basestring, you can also simplify the above code to:
>>> isinstance(u'a', basestring) True
Since we have type() to determine the type, why is there isinstance()? One obvious difference is in judging subclasses. type() does not consider a subclass to be a parent type. isinstance() will consider the subclass to be a parent class type.
The above is the detailed content of How to check the type of an object. For more information, please follow other related articles on the PHP Chinese website!