Let\'s say that I have a class Suit and four subclasses of suit: Heart, Spade, Diamond, Club.
class Suit:
...
class Heart(Suit):
...
class Spade(Suit):
issubclass(class, classinfo)
Excerpt:
Return true if
class
is a subclass (direct, indirect or virtual) ofclassinfo
.
You can use isinstance
if you have an instance, or issubclass
if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.
The issubclass(sub, sup)
boolean function returns true if the given subclass sub
is indeed a subclass of the superclass sup
.
issubclass
minimal runnable example
Here is a more complete example with some assertions:
#!/usr/bin/env python3
class Base:
pass
class Derived(Base):
pass
base = Base()
derived = Derived()
# Basic usage.
assert issubclass(Derived, Base)
assert not issubclass(Base, Derived)
# True for same object.
assert issubclass(Base, Base)
# Cannot use object of class.
try:
issubclass(derived, Base)
except TypeError:
pass
else:
assert False
# Do this instead.
assert isinstance(derived, Base)
GitHub upstream.
Tested in Python 3.5.2.
#issubclass(child,parent)
class a:
pass
class b(a):
pass
class c(b):
pass
print(issubclass(c,b))#it returns true
You can use issubclass()
like this assert issubclass(suit, Suit)
.