How do I check (at runtime) if one class is a subclass of another?

前端 未结 9 1750
忘了有多久
忘了有多久 2020-11-28 05:40

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):         


        
相关标签:
9条回答
  • 2020-11-28 06:02

    You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.

    0 讨论(0)
  • 2020-11-28 06:06

    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
    
    0 讨论(0)
  • 2020-11-28 06:07

    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)
    
    0 讨论(0)
提交回复
热议问题