动态修改父类私有函数对象

class C(object):
    def public_method(self):
        self.__private_method()
        
    def __private_method(self):
        print(self)
        print("c_private_method")
        self.__private_method2()

    def __private_method2(self):
        print("c_private_method2")

    @staticmethod
    def static_method():
        print("c static method")

class D(C):
    func_obj = None

    def __init__(self):
        if not D.__is_override():
            D.__override_private_method()

    def __private_method(self):
        print(D.func_obj)
        print(self)
        print("d_private_method")
        D.func_obj(self)
    
    @classmethod
    def __override_private_method(cls, ):
        cls.func_obj = getattr(C, "_C__private_method")
        setattr(C, "_C__private_method", getattr(cls, "_D__private_method"))
    
    @classmethod
    def __is_override(cls):
        return D.func_obj is not None

if __name__ == "__main__":
    D().public_method()
    print("---")
    D().public_method()

猜你喜欢

转载自www.cnblogs.com/wenlin-gk/p/10542992.html