在 Python 中检查 A 是否是 B 的超类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1938755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:23:46  来源:igfitidea点击:

Checking if A is superclass of B in Python

pythonreflectionsuperclass

提问by Andz

class p1(object): pass
class p2(p1): pass

So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ?

所以 p2 是 p1 的子类。有没有办法以编程方式找出 p1 是 p2 的超类 [es] 之一?

回答by user235859

using <class>.__bases__ seems to be what you're looking for...

使用 <class>.__bases__ 似乎是你正在寻找的......

>>> class p1(object): pass
>>> class p2(p1): pass
>>> p2.__bases__
(<class '__main__.p1'>,)

回答by Serge

Yes, there is way. You can use a issubclassfunction.

是的,有办法。您可以使用issubclass函数。

As follows:

如下:

class p1(object):pass
class p2(p1):pass

issubclass(p2, p1)

回答by Azeem.Butt

Depending on what you're trying to do, the "mro" method can also be useful.

根据您尝试执行的操作,“mro”方法也很有用。

回答by Joril

I think you meant to use "class" instead of "def".. :) Anyway, try p2.__bases__

我认为您打算使用“class”而不是“def”.. :) 无论如何,请尝试 p2.__bases__