isinstance 替代检查 类 which return flase on being parent or subclass

isinstance alternative to check classes which return flase on being the parent or subclass

让我先展示一下 isinstance() 是如何工作的

class superclass:
    def __init__(self, var):
        self.var = var

class subclass(p):
    pass

obj = subclass("pinoy")

isinstance 是这样工作的

>>> isinstance (obj, superclass)
True

这里,obj主要是subclass的一个实例。因为,subclass 继承自 superclass

isinstance(obj, superclass) returns True

是否有任何方法可以检查对象是否主要属于指定的 class,否则 return Flase

你可以使用 type:

class superclass:
    def __init__(self, var):
        self.var = var

class subclass(superclass):
    pass
obj = subclass("pinoy")

print(type(obj))
#<class '__main__.subclass'>

type(obj) == subclass
# True

type(obj) == superclass
# False