Python - isinstance(classInfo, classInfo)

2.9k Views Asked by At

The Python documentation says that isinstance requires an instance object of a class and the class info. The problem is: I just have 2 class info object and have to check if class_inf1 is a instance of class_inf2

Example:

class Foo(object):
    pass

class Bar(Foo):
    pass

# It should check if Bar is a instance of Foo. Bar can either be one of many subclasses or 
# the same class.
isinstance(Bar, Foo)

# i.e.: the function I'm looking for should be working as if Bar was an object:
isinstance(Bar(), Foo)

In my more complex code, I can't know what Bar is because it is a variable. I can't initialize it because I don't know what parameters it takes and it might do some nasty things, too. (And I will never need to initialize this variable because it is kind of a test).

1

There are 1 best solutions below

1
AudioBubble On BEST ANSWER

Your terminology is rather confused, but my best guess is that you want to check whether one class inherits from another. This is achieved via the issubclass builtin:

class B(object):
    pass

class D(B):
    pass

print issubclass(B, object)
print issubclass(D, B) # true
# order matters:
print issubclass(B, D) # false
# it's transitive:
print issubclass(D, object)
# a class is a subclass of itself:
print issubclass(B, B) # true