Home > Backend Development > Python Tutorial > The difference between python data type judgment type and isinstance

The difference between python data type judgment type and isinstance

高洛峰
Release: 2016-10-19 14:39:05
Original
1833 people have browsed it

In the project, we will verify the parameter type passed by the client on each interface. If the verification fails, a "parameter error" error code will be returned to the client.

This not only facilitates debugging, but also increases robustness. Because the client can cheat, don't trust the parameters passed by the client easily.

Verify the type using the type function, which is very easy to use, such as

>>type('foo') == str

True

>>type(2.3) in (int, float)

True

Since there is Type() is used to determine the type, why is there isinstance()?

An obvious difference is in judging subclasses.

type() will not consider the subclass to be a parent class type.

isinstance() will consider the subclass to be a parent class type.

A thousand words are worth a yard.

class Foo(object):
    pass
    
class Bar(Foo):
    pass
    
print type(Foo()) == Foo
print type(Bar()) == Foo
print isinstance(Bar(),Foo)
   
class Foo(object):
    pass
   
class Bar(Foo):
    pass
   
print type(Foo()) == Foo
print type(Bar()) == Foo
print isinstance(Bar(),Foo)
输出
True
False
True
Copy after login

It should be noted that the type() results of old-style classes and new-style classes are different. Old-style classes are all .

class A:
    pass
    
class B:
    pass
    
class C(object):
    pass
    
print 'old style class',type(A())
print 'old style class',type(B())
print 'new style class',type(C())
print type(A()) == type(B())
   
class A:
    pass
   
class B:
    pass
   
class C(object):
    pass
   
print 'old style class',type(A())
print 'old style class',type(B())
print 'new style class',type(C())
print type(A()) == type(B())
输出
old style class <type &#39;instance&#39;>
old style class <type &#39;instance&#39;>
new style class <class &#39;__main__.C&#39;>
True
Copy after login

There is no saying that isinstance is better than type. Only which one better suits the needs.

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template