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

前端 未结 9 1749
忘了有多久
忘了有多久 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 05:51

    issubclass(class, classinfo)

    Excerpt:

    Return true if class is a subclass (direct, indirect or virtual) of classinfo.

    0 讨论(0)
  • 2020-11-28 05:53

    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.

    0 讨论(0)
  • 2020-11-28 05:54

    The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.

    0 讨论(0)
  • 2020-11-28 05:55

    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.

    0 讨论(0)
  • 2020-11-28 05:57
    #issubclass(child,parent)
    
    class a:
        pass
    class b(a):
        pass
    class c(b):
        pass
    
    print(issubclass(c,b))#it returns true
    
    0 讨论(0)
  • 2020-11-28 06:00

    You can use issubclass() like this assert issubclass(suit, Suit).

    0 讨论(0)
提交回复
热议问题