获取子类的重写函数

Get overridden functions of subclass

有没有办法获取 Python 中子 class 的所有重写函数?

示例:

class A:
    def a1(self):
        pass

    def a2(self):
        pass


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

    def b1(self):
        pass

在这里,我想获取 class B 对象(或 class 对象本身)的列表 ["a2"],因为 class B 只覆盖一个方法,即 a2.

您可以使用 __mro__ 元组,它包含方法解析顺序。

以你的例子为例:

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

因此您可以遍历该元组并检查 B 方法是否也在另一个 类.

您可以通过 cls.__bases__, find all attributes of the parents with dir, and access all the attributes of the class itself with 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)
>>> get_overridden_methods(B)
{'a2'}
class A:

    def a1(self):
        pass

    def a2(self):
        pass


class B(A):

    def a2(self):
        super().a2()  
        pass

    def b1(self):
        pass
obj = B()

obj.a2()   # ***first give the output of parent class then child class***