Getting all superclasses in python 3

旧街凉风 提交于 2019-12-10 17:21:53

问题


How I can get a list with all superclasses of given class in python?

I know, there is a __subclasses__() method in inspent module for getting all subclasses, but I don't know any similar method for getting superclasses.

Can you help me?


回答1:


Use the mro method:

>>> class A(object):
    pass


>>> class B(object):
    pass


>>> class C(A, B):
    pass

>>> C.mro()
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>]



回答2:


Here's 2 methods which work both for python 2 and 3.

Argument can be an instance or a classe.

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


来源:https://stackoverflow.com/questions/31028237/getting-all-superclasses-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!