获取子类的重写函数

And*_*mer 19 python reflection overriding subclass

有没有办法在Python中获取子类的所有替代函数?

例:

class A:
    def a1(self):
        pass

    def a2(self):
        pass


class B(A):
    def a2(self):
        pass

    def b1(self):
        pass
Run Code Online (Sandbox Code Playgroud)

在这里,我想获得一个列表["a2"]的类的对象B(或类对象本身),因为类B重写只有一个方法,即a2

Ara*_*Fey 17

您可以使用访问父类cls.__bases__,使用查找父类的所有属性dir,并使用以下命令访问类本身的所有属性vars

def get_overridden_methods(cls):
    # collect all attributes inherited from parent classes
    parent_attrs = set()
    for base in cls.__bases__:
        parent_attrs.update(dir(base))

    # find all methods implemented in the class itself
    methods = {name for name, thing in vars(cls).items() if callable(thing)}

    # return the intersection of both
    return parent_attrs.intersection(methods)
Run Code Online (Sandbox Code Playgroud)
>>> get_overridden_methods(B)
{'a2'}
Run Code Online (Sandbox Code Playgroud)