在Python3中获取所有超类

2024-09-30 22:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获得Python中给定类的所有超类的列表

我知道,在inspent模块中有一个__subclasses__()方法用于获取所有子类,但我不知道任何类似的方法用于获取超类


Tags: 模块方法列表子类subclassesinspent
2条回答

这里有两种方法同时适用于Python2和Python3

参数可以是实例或类

import inspect

# Works both for python 2 and 3
def getClassName(anObject):    
    if (inspect.isclass(anObject) == False): anObject = anObject.__class__
    className = anObject.__name__
    return className

# Works both for python 2 and 3
def getSuperClassNames(anObject):
    superClassNames = []
    if (inspect.isclass(anObject) == False): anObject = anObject.__class__
    classes = inspect.getmro(anObject)
    for cl in classes:
        s = str(cl).replace('\'', '').replace('>', '')
        if ("__main__." in s): superClassNames.append(s.split('.', 1)[1])
    clName = str(anObject.__name__)
    if (clName in superClassNames): superClassNames.remove(clName)
    if (len(superClassNames) == 0): superClassNames = None
    return superClassNames

使用__mro__属性:

>>> class A:
...     pass
...
>>> class B:
...     pass
...
>>> class C(A, B):
...     pass
...
>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

这是在类实例化时填充的special attribute

class.__mro__ This attribute is a tuple of classes that are considered when looking for base classes during method resolution.

class.mro() This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__.

相关问题 更多 >