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)
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.
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.
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.
The issubclass() function returns True if the specified object is a subclass of the specified object, otherwise False .
issubclass only works for instances, not class objects themselves.
It works fine for me:
>>> class test(object):pass
...
>>> issubclass(test,object)
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With