如何(在运行时)检查一个类是否是另一个类的子类?
问题描述:
比方说,我有一个西服套装和四个西服套装子类别:Heart,Spade,Diamond和Club.
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):
...
我有一个方法,该方法接收西服作为参数,这是一个类对象,而不是实例.更准确地说,它可能仅接收以下四个值之一:Heart,Spade,Diamond,Club.我该如何做出保证这种事情的断言?像这样:
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)
...
我正在使用Python 3.
I'm using Python 3.
答
您可以像assert issubclass(suit, Suit)
这样使用issubclass()
.