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):
You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.
According to the Python doc, we can also use class.__mro__
attribute or class.mro()
method:
class Suit:
pass
class Heart(Suit):
pass
class Spade(Suit):
pass
class Diamond(Suit):
pass
class Club(Suit):
pass
>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)
Suit in Heart.mro() # True
object in Heart.__mro__ # True
Spade in Heart.mro() # False
Using issubclass seemed like a clean way to write loglevels. It kinda feels odd using it... but it seems cleaner than other options.
class Error(object): pass
class Warn(Error): pass
class Info(Warn): pass
class Debug(Info): pass
class Logger():
LEVEL = Info
@staticmethod
def log(text,level):
if issubclass(Logger.LEVEL,level):
print(text)
@staticmethod
def debug(text):
Logger.log(text,Debug)
@staticmethod
def info(text):
Logger.log(text,Info)
@staticmethod
def warn(text):
Logger.log(text,Warn)
@staticmethod
def error(text):
Logger.log(text,Error)