Detailed introduction to Python's built-in isinstance function

高洛峰
Release: 2017-03-21 09:32:20
Original
1948 people have browsed it

English documentation:

isinstance(object,classinfo)

Returntrueifthe object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeErrorexceptionis raised.

Description:

1.FunctionThe function is used to determine whether the object is an instance of a type object. The object parameter indicates the object that needs to be checked, and the calssinfo parameter indicates the type object.

 2. If the object parameter is an instance of a classinfo type object (or a direct, indirect, or virtual subclass of a classinfo class object), return True.

>>> isinstance(1,int) True >>> isinstance(1,str) False # 定义3各类:C继承B,B继承A >>> class A: pass >>> class B(A): pass >>> class C(B): pass >>> a = A() >>> b = B() >>> c = C() >>> isinstance(a,A) #直接实例 True >>> isinstance(a,B) False >>> isinstance(b,A) #子类实例 True >>> isinstance(c,A) #孙子类实例 True
Copy after login

 3. If the object parameter is passed in a type object, False will always be returned.

>>> isinstance(str,str) False >>> isinstance(bool,int) False
Copy after login

 4. If the classinfo type object is a tuple composed of multiple type objects, and ifobject objectis an instance of any type object in the tuple, return True, otherwise return False.

>>> isinstance(a,(B,C)) False >>> isinstance(a,(A,B,C)) True
Copy after login

 5. If the classinfo type object is not a type object or a tuple composed of multiple type objects, an error (TypeError) will be reported.

>>> isinstance(a,[A,B,C]) Traceback (most recent call last): File "", line 1, in  isinstance(a,[A,B,C]) TypeError: isinstance() arg 2 must be a type or tuple of types
Copy after login

The above is the detailed content of Detailed introduction to Python's built-in isinstance function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!