Python:重写基类中的助手函数调用

Python:重写基类中的助手函数调用,python,inheritance,overriding,Python,Inheritance,Overriding,这在python中可以实现吗 单元A: def _helper: print('helper_a') class A(): def foo(self): _helper() 模块B: def _helper: print('helper_b') class B(A): """ Somehow make B.foo call module B _helper without overriding A.foo""" _helper只是模块a中的

这在python中可以实现吗

单元A:

def _helper:
    print('helper_a')

class A():
    def foo(self):
        _helper()
模块B:

def _helper:
    print('helper_b')

class B(A):
    """ Somehow make B.foo call module B _helper without overriding A.foo"""
_helper只是模块a中的一个全局变量。您可以将其设置为其他变量,然后对a.foo的调用将使用该新的全局变量。这就是所谓的猴子修补术

但是,如果只想在使用类B时修补_helper,那么每次都必须修补和取消修补。这是可以做到的,但不是线程安全的,通常只有在您无法重构模块A时才能使用:

class B(A):
    def foo(self):
        orig_helper = moduleA._helper
        moduleA._helper = _helper
        try:
            return super().foo()
        finally:
            moduleA._helper = orig_helper
您也可以在类B上重写foo:

如果可以重构模块A,则可以将_helper函数作为类上的静态函数:

class A():
    @staticmethod
    def _helper():
        print('helper_a')

    def foo(self):
        self._helper()
此时,您可以在B上提供替代版本:


等。

当你打电话给B.foo时,你预计会发生什么?你可以查一下名字ManglingThank Martijn,这正是我要找的信息,非常有用。
class A():
    @staticmethod
    def _helper():
        print('helper_a')

    def foo(self):
        self._helper()
class B():
    @staticmethod
    def _helper():
        print('helper_b')