Python:检查两个变量之间相同类型的最佳方法

Lia*_*hav 5 python types isinstance python-3.x

我正在检查 python 3.x 中两个变量是否具有相同的类型。做到这一点最理想的方法是什么?

举个例子:

class A():
    def __init__(self, x):
        self.x = x

class B(A):
    def __init__(self, x):
        x += 5
        super(B, self).__init__(x)
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想返回True两个类型为A和的变量B是否相互比较。以下是一些可能不起作用的解决方案:

>>> a = A(5)
>>> b = B(5)
>>>
>>> type(a) is type(b)
False
>>> isinstance(a, type(b))
False
>>> isinstance(b, type(a))
True
Run Code Online (Sandbox Code Playgroud)

最后一个并不理想,因为如中间示例所示,如果要检查的类型是变量类型的子类,False则返回。

我尝试过的唯一可以涵盖这里所有基础的解决方案是:

>>> isinstance(a, type(b)) or isinstance(b, type(a))
True
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

And*_*ely 2

该程序遍历所有__bases__提供的对象并检查它们之间的公共交集(sans object):

class A:
    def __init__(self, x):
        self.x = x

class B(A):
    def __init__(self, x):
        x += 5
        super(B, self).__init__(x)

class C(B):
    def __init__(self, x):
        self.x = x

class D:
    def __init__(self, x):
        self.x = x

class E(C, B):
    def __init__(self, x):
        self.x = x

a = A(5)
b = B(5)
c = C(5)
d = D(5)
e = E(5)

def check(*objs):
    def _all_bases(o):
        for b in o.__bases__:
            if b is not object:
                yield b
            yield from _all_bases(b)
    s = [(i.__class__, *_all_bases(i.__class__)) for i in objs]
    return len(set(*s[:1]).intersection(*s[1:])) > 0

print(check(a, b)) # True
print(check(a, c)) # True
print(check(a, d)) # False
print(check(a, e)) # True
print(check(b, c)) # True
print(check(b, d)) # False
print(check(b, e)) # True
print(check(e, d)) # False
print(check(a, b, c)) # True
print(check(a, b, c, e)) # True
print(check(a, b, c, d)) # False
print(check('string1', 'string2')) # True
Run Code Online (Sandbox Code Playgroud)