本文介绍了如何检查(在运行时)一个类是否是另一个类的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个套装和四个子套装: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.
推荐答案
你可以像这样使用 issubclass()
assert issubclass(suit, Suit)
.
You can use issubclass()
like this assert issubclass(suit, Suit)
.
这篇关于如何检查(在运行时)一个类是否是另一个类的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!