Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a class is descended from another class

Tags:

python

I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class or a subclass of that, I need to pass it in to one of two other (third-party) factory functions.

(To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party library accepts.)

issubclass only works for instances, not class objects themselves. I suppose I could instantiate the class, do issubclass and throw away the instance, but that seems a bit wasteful.

Here's what I'm doing at the moment, relying on the built-in mro attribute to tell if a certain class is in the list of ancestors of my class. Is this safe, and is there any better way of doing it?

if GenericClass in myclass.__mro__:
    result = generic_factory(myclass)
else:
    result = other_factory(myclass)
like image 202
Daniel Roseman Avatar asked May 19 '09 09:05

Daniel Roseman


People also ask

How do I know if my class is a child of another class?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

How do you know if a class inherits from another Java?

If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class). For your example, it would be: if(B. class.

How do you determine if a certain class is a subclass of another class Java?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

What is Issubclass?

The issubclass() function returns True if the specified object is a subclass of the specified object, otherwise False .


1 Answers

issubclass only works for instances, not class objects themselves.

It works fine for me:

>>> class test(object):pass
...
>>> issubclass(test,object)
True
like image 143
Unknown Avatar answered Sep 22 '22 05:09

Unknown