如何(在运行时)检查一个类是否是另一个类的子类?
假设我有一个花色类和四个花色子类:红心、黑桃、方块、梅花。
class Suit:
...
class Heart(Suit):
...
class Spade(Suit):
...
class Diamond(Suit):
...
class Club(Suit):
...
我有一个方法,它接收西装作为参数,它是一个类对象,而不是一个实例。更准确地说,它可能只接收四个值之一:Heart、Spade、Diamond、Club。我怎样才能做出确保这样的事情的断言?比如:
def my_method(suit):
assert(suit subclass of Suit)
...
我正在使用 Python 3。
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):
...
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)
...
I'm using Python 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您可以像
assert issubclass(suit, Suit)
一样使用issubclass()
。You can use
issubclass()
like thisassert issubclass(suit, Suit)
.issubclass(class, classinfo)
摘录:
issubclass(class, classinfo)
Excerpt:
如果您有实例,则可以使用
isinstance
;如果您有类,则可以使用issubclass
。通常认为这是一个坏主意。通常,在 Python 中,你可以通过尝试对某个对象执行某件事来确定该对象是否能够执行该操作。You can use
isinstance
if you have an instance, orissubclass
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.如果给定子类
sub
确实是超类sup
的子类,则issubclass(sub, sep)
布尔函数返回 true。The
issubclass(sub, sup)
boolean function returns true if the given subclasssub
is indeed a subclass of the superclasssup
.issubclass
最小可运行示例这是一个包含一些断言的更完整示例:
GitHub 上游。
在 Python 3.5.2 中测试。
issubclass
minimal runnable exampleHere is a more complete example with some assertions:
GitHub upstream.
Tested in Python 3.5.2.
根据 Python doc,我们还可以使用
class.__mro__
属性或class.mro()
方法:According to the Python doc, we can also use
class.__mro__
attribute orclass.mro()
method:@snakile,使用此代码:
输出:
@snakile, use this code:
Output:
您可以使用内置的 issubclass。但类型检查通常被认为是不必要的,因为您可以使用鸭子类型。
You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.
使用 issubclass 似乎是一种编写日志级别的干净方法。使用它感觉有点奇怪......但它看起来比其他选项更干净。
Using issubclass seemed like a clean way to write loglevels. It kinda feels odd using it... but it seems cleaner than other options.