This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
To determine whether a variable is a data type, you can use either isinstance() or type().
type()
class
type
(name, bases, dict, **kwds)
- Returns when passed a parameterobjectThe type of. The return value is a Type object, usually the same as
object.__class__
The same object is returned.When three arguments are passed, a new Type object is returned.(No, don’t look)
nameThe string is the class name and will become;__name__
attributebasesTuples contain base classes and become.__bases__
Properties; If empty, the ultimate base class for all classes is addedobject
dictThe dictionary contains the attributes and method definitions of the class body; It became a.__dict__
Attributes may have been copied or wrapped previously
Use it to determine the data type:
s = 'hello world'
print(type(s) == str)
Copy the code
>>
True
Copy the code
isinstance()
isinstance
(object, classinfo)
- ifobjectThe parameter isclassinfoAn instance of a parameter, or its (directly, indirectly, orvirtual), returns an instance of a subclass
True
. ifobjectObjects that are not of the given type are always returnedFalse
.- ifclassinfoIs a tuple of an object of type (or generated recursively by that tuple) or more typesThe union type, then whenobjectIs returned when it is an instance of any of these types
True
. ifclassinfoIs not a type or type tuple, will fireTypeError
The exception.
Use it to determine the data type:
s = 'hello world'
print(isinstance(s,str))
Copy the code
>>
True
Copy the code
You can also do this:
s = 'hello world'
print(isinstance(s,(str.int.float)))
print(isinstance(s,(bool.int.float)))
Copy the code
>>
True
False
Copy the code
Isinstance () differs from type()
- Type () does not consider a subclass to be a parent type, regardless of inheritance.
- Isinstance () considers a subclass to be a superclass type, considering inheritance.
It is recommended to use isinstance() to determine whether two types are the same.
Because:
class F:
def __init__(self) :
pass
class S(F) :
def __init__(self) :
pass
print(isinstance(F(), F))
print(type(F()) == F)
print(isinstance(S(), F))
print(type(S()) == F)
Copy the code
True
True
True
False
Copy the code
This shows that isinstance() is more powerful, so isinstance() is recommended to determine whether two types are the same.