Python inheritance - how to disable a function

前端 未结 7 880
离开以前
离开以前 2020-12-01 04:18

In C++ you can disable a function in parent\'s class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent\'s function fr

7条回答
  •  星月不相逢
    2020-12-01 04:53

    That could be even simpler.

    @property
    def private(self):
        raise AttributeError
    
    class A:
        def __init__(self):
            pass
        def hello(self):
            print("Hello World")
    
    class B(A):
        hello = private # that short, really
        def hi(self):
            A.hello(self)
    
    obj = A()
    obj.hello()
    obj = B()
    obj.hi() # works
    obj.hello() # raises AttributeError
    

提交回复
热议问题