Python inheritance - how to disable a function

前端 未结 7 877
离开以前
离开以前 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:17

    kurosch's method of solving the problem isn't quite correct, because you can still use b.foo without getting an AttributeError. If you don't invoke the function, no error occurs. Here are two ways that I can think to do this:

    import doctest
    
    class Foo(object):
        """
        >>> Foo().foo()
        foo
        """
        def foo(self): print 'foo'
        def fu(self): print 'fu'
    
    class Bar(object):
        """
        >>> b = Bar()
        >>> b.foo()
        Traceback (most recent call last):
        ...
        AttributeError
        >>> hasattr(b, 'foo')
        False
        >>> hasattr(b, 'fu')
        True
        """
        def __init__(self): self._wrapped = Foo()
    
        def __getattr__(self, attr_name):
            if attr_name == 'foo': raise AttributeError
            return getattr(self._wrapped, attr_name)
    
    class Baz(Foo):
        """
        >>> b = Baz()
        >>> b.foo() # doctest: +ELLIPSIS
        Traceback (most recent call last):
        ...
        AttributeError...
        >>> hasattr(b, 'foo')
        False
        >>> hasattr(b, 'fu')
        True
        """
        foo = property()
    
    if __name__ == '__main__':
        doctest.testmod()
    

    Bar uses the "wrap" pattern to restrict access to the wrapped object. Martelli has a good talk dealing with this. Baz uses the property built-in to implement the descriptor protocol for the attribute to override.

    0 讨论(0)
提交回复
热议问题