2010-05-13 3 views
28

이 질문은 많은 가정의 위에 만들어집니다. 한 가정이 틀린다면, 모든 것이 넘어집니다. 나는 여전히 Python에 처음으로 익숙하며 흥미롭고 탐험적인 단계에 접어 들었습니다.Python 3.x의 최종 수업 - 귀도가 나에게 말하지 않는 것?

그것은 파이썬은 서브 클래스화할 수없는 클래스의 생성 (최종 클래스)를 지원하지 않는 나의 이해이다. 그러나, 내게 그것은 bool 클래스를 파이썬으로 서브 클래 싱 할 수 없다고 생각합니다. 이것은 bool 클래스의 의도가 고려 될 때 (bool은 true와 false의 두 값만 있기 때문에) 이해할 수 있습니다. 그 점에 만족합니다. 내가 알고 싶은 것은 입니다.이 등급이 최종으로 표시되었습니다.

내 질문은 : Guido가 bool의 서브 클래 싱을 방지하기 위해 정확히 관리하는 방법은 무엇입니까?

>>> class TestClass(bool): 
     pass 

Traceback (most recent call last): 
    File "<pyshell#2>", line 1, in <module> 
    class TestClass(bool): 
TypeError: type 'bool' is not an acceptable base type 

관련 질문 :Why I can't extend bool in Python?

답변

40

당신은 아주 쉽게 파이썬 3.x의에서 같은 효과를 시뮬레이션 할 수 있습니다 : 문서에

Traceback (most recent call last): 
    File "C:\Temp\final.py", line 10, in <module> 
    class D(C): pass 
    File "C:\Temp\final.py", line 5, in __new__ 
    raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__)) 
TypeError: type 'C' is not an acceptable base type 
11

당신은 단지 C API를 통해이 작업을 수행 할 수 있습니다. 개체 유형이 tp_flagsPy_TPFLAGS_BASETYPE 비트를 지 웁니다.

다음과 같이하십시오 : http://svn.python.org/projects/python/trunk/Objects/boolobject.c (vs intobject.c, 여기서 Py_TPFLAGS_BASETYPE이 설정 됨).

+0

링크 : http://docs.python.org

class Final(type): def __new__(cls, name, bases, classdict): for b in bases: if isinstance(b, Final): raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__)) return type.__new__(cls, name, bases, dict(classdict)) class C(metaclass=Final): pass class D(C): pass 

다음과 같은 출력을 줄 것이다 /c-api/typeobj.html#Py_TPFLAGS_BASETYPE –

관련 문제