Python inheritance - how to disable a function

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

    There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:

    >>> class Foo( object ):
    ...     def foo( self ):
    ...         print 'FOO!'
    ...         
    >>> class Bar( Foo ):
    ...     def foo( self ):
    ...         raise AttributeError( "'Bar' object has no attribute 'foo'" )
    ...     
    >>> b = Bar()
    >>> b.foo()
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 3, in foo
    AttributeError: 'Bar' object has no attribute 'foo'
    

提交回复
热议问题