Search code examples
pythonobjectisinstance

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


Let me first show how isinstance() works

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

class subclass(p):
    pass

obj = subclass("pinoy")

This is how isinstance works

>>> isinstance (obj, superclass)
True

Here, obj is mainly a instance of subclass. Since, subclass inherits from superclass,

isinstance(obj, superclass) returns True

Is there any, way that would check if a object mainly belongs to the class specified and return Flase otherwise.


Solution

  • You could use 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