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(namebasesdict,  **kwds)

  • Returns when passed a parameterobjectThe type of. The return value is a Type object, usually the same asobject.__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__attribute;
    • basesTuples 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(objectclassinfo)

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.