python issubclass and isinstance functions
- 2021-07-26 08:24:11
- OfStack
Python issubclass () Function
issubclass() Method is used to determine parameters class Is it a type parameter classinfo Gets or sets a subclass of.
Syntax:
issubclass(class, classinfo)
Parameter
class -- Class.
classinfo -- Class.
Return value
If class Yes classinfo Returns a subclass of True Otherwise, return False .
Examples:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class A:
pass
class B(A):
pass
print(issubclass(B,A)) # Return True
Python isinstance () Function
isinstance() Function to judge 1 Is the object 1 A known type, similar to type() .
isinstance() And type() Difference:
type() Does not consider a subclass to be 1 Species parent class type, regardless of inheritance relationship.
isinstance() Will think that subclasses are 1 Species parent class type, considering inheritance relationship.
If you want to determine whether two types are the same, it is recommended to use isinstance() .
Syntax:
isinstance(object, classinfo)
Parameter
object -- Instance object.
classinfo -- It can be a direct or indirect class name, a base type, or a tuple composed of them.
Return value
If the type and parameters of the object 2 The type of the ( classinfo ) Is the same True Otherwise, return False .
Examples:
>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # Is in the tuple 1 Return True
True
type() And isinstance() Difference:
class A: pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
Summarize