How to compare type of an object in Python?

后端 未结 14 2437
闹比i
闹比i 2020-11-28 01:26

Basically I want to do this:

obj = \'str\'
type ( obj ) == string

I tried:

type ( obj ) == type ( string )
<
14条回答
  •  -上瘾入骨i
    2020-11-28 02:00

    You can compare classes for check level.

    #!/usr/bin/env python
    #coding:utf8
    
    class A(object):
        def t(self):
            print 'A'
        def r(self):
            print 'rA',
            self.t()
    
    class B(A):
        def t(self):
            print 'B'
    
    class C(A):
        def t(self):
            print 'C'
    
    class D(B, C):
        def t(self):
            print 'D',
            super(D, self).t()
    
    class E(C, B):
        pass
    
    d = D()
    d.t()
    d.r()
    
    e = E()
    e.t()
    e.r()
    
    print isinstance(e, D) # False
    print isinstance(e, E) # True
    print isinstance(e, C) # True
    print isinstance(e, B) # True
    print isinstance(e, (A,)) # True
    print e.__class__ >= A, #False
    print e.__class__ <= C, #False
    print e.__class__ <  E, #False
    print e.__class__ <= E  #True
    

提交回复
热议问题