Python inheritance - how to disable a function

前端 未结 7 879
离开以前
离开以前 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 05:14

    Another approach is define an descriptor that errors on access.

        class NotHereDescriptor:
            def __get__(self, obj, type=None):
                raise AttributeError
        
        class Bar:
            foo = NotHereDescriptor()
    

    This is similar in nature to the property approach a few people have used above. However it has the advantage that hasattr(Bar, 'foo') will return False as one would expect if the function really didn't exist. Which further reduces the chance of weird bugs. Although it does still show up in dir(Bar).

    If you are interested in what this is doing and why it works check out the descriptor section of the data model page https://docs.python.org/3/reference/datamodel.html#descriptors and the descriptor how to https://docs.python.org/3/howto/descriptor.html

提交回复
热议问题