Artaza Sameen
Artaza Sameen

Reputation: 787

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.

Upvotes: 1

Views: 603

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

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

Upvotes: 3

Related Questions