문제

에서는 C++를 사용하지 않도록 설정할 수 있습니다 기능에서 부모의 클래스를 선언하여 그것은 개인으로서 아이 클래스입니다.이것을 어떻게 할 수 있는 파이썬?I.E.나는 어떻게 숨기는 부모의 함수에서 아이의 공공하시겠습니까?

도움이 되었습니까?

해결책

파이썬에는 실제로 "개인"속성이나 방법이 없습니다. 당신이 할 수있는 한 가지는 단순히 서브 클래스에서 원하지 않는 메소드를 무시하고 예외를 제기하는 것입니다.

>>> 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()

바을 사용하"랩"패턴에 대한 액세스를 제한하는 감 개체입니다. 마르텔리는 좋은 이야기 를 처리합니다.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

이것은 an을 올립니다 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")

이것이 내가하는 가장 깨끗한 방법입니다.

메소드를 무시하고 비정규 메소드를 비활성화 한 메소드를 호출하도록하십시오 () 메소드를 호출하십시오. 이와 같이:

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