在C ++中,您可以通过在子类中将其声明为私有来禁用父类中的函数。如何在Python中完成? I.E.如何从子的公共界面隐藏父级功能?

有帮助吗?

解决方案

确实没有任何真正的“私人” Python中的属性或方法。您可以做的一件事就是简单地覆盖子类中不需要的方法,并引发异常:

>>> 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 "<interactive input>", line 1, in <module>
  File "<interactive input>", line 3, in foo
AttributeError: 'Bar' object has no attribute 'foo'

其他提示

kurosch解决问题的方法并不完全正确,因为您仍然可以使用 b.foo 而无需获取 AttributeError 。如果不调用该函数,则不会发生错误。我有两种方法可以做到这一点:

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使用“wrap”方法。用于限制对包装对象的访问的模式。 Martelli有一个很好的谈话处理这个问题。 Baz使用内置属性来实现描述符协议要覆盖的属性。

kurosch答案的变体:

class Foo( object ):
    def foo( self ):
        print 'FOO!'

class Bar( Foo ):
    @property
    def foo( self ):
        raise AttributeError( "'Bar' object has no attribute 'foo'" )

b = Bar()
b.foo

这会在属性上引发 AttributeError ,而不是在调用方法时。

我会在评论中提出这个问题,但遗憾的是还没有它的声誉。

class X(object):
    def some_function(self):
        do_some_stuff()

class Y(object):
    some_function = None

这可能会导致一些令人讨厌且难以发现的异常被抛出,所以你可以试试这个:

class X(object):
    def some_function(self):
        do_some_stuff()

class Y(object):
    def some_function(self):
        raise NotImplementedError("function some_function not implemented")

这是我所知道的最干净的方式。

重写方法并让每个重写的方法调用disabledmethods()方法。像这样:

class Deck(list):
...
@staticmethod
    def disabledmethods():
        raise Exception('Function Disabled')
    def pop(self): Deck.disabledmethods()
    def sort(self): Deck.disabledmethods()
    def reverse(self): Deck.disabledmethods()
    def __setitem__(self, loc, val): Deck.disabledmethods()

这可能更简单。

@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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top