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):
...
class Diamond(Suit):
...
class Club(Suit):
...
I have a method which receives a suit as a parameter, which is a class object, not an instance. More precisely, it may receive only one of the four values: Heart, Spade, Diamond, Club. How can I make an assertion which ensures such a thing? Something like:
def my_method(suit):
assert(suit subclass of Suit)
...
I'm using Python 3.
Using issubclass seemed like a clean way to write loglevels. It kinda feels odd using it... but it seems cleaner than other options.
You can use
isinstance
if you have an instance, orissubclass
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 subclasssub
is indeed a subclass of the superclasssup
.