Bor*_*lik 31 python inheritance private interface
在C++中,您可以通过在子类中将其声明为私有来禁用父类中的函数.如何在Python中完成?IE如何从子公共接口隐藏父功能?
kur*_*sch 23
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'
Run Code Online (Sandbox Code Playgroud)
cdl*_*ary 18
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()
Run Code Online (Sandbox Code Playgroud)
Bar使用"wrap"模式来限制对包装对象的访问.Martelli对此有一个很好的谈话.Baz使用内置属性来实现要覆盖的属性的描述符协议.
Joh*_*men 11
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
Run Code Online (Sandbox Code Playgroud)
这会引发AttributeError
属性,而不是调用方法时.
我会在评论中提出这个问题,但遗憾的是还没有它的声誉.
class X(object):
def some_function(self):
do_some_stuff()
class Y(object):
some_function = None
Run Code Online (Sandbox Code Playgroud)
这可能会导致一些令人讨厌且难以发现的异常被抛出,所以你可以试试这个:
class X(object):
def some_function(self):
do_some_stuff()
class Y(object):
def some_function(self):
raise NotImplementedError("function some_function not implemented")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16797 次 |
最近记录: |