Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

inheritance - Final classes in Python 3.x- something Guido isn't telling me?

This question is built on top of many assumptions. If one assumption is wrong, then the whole thing falls over. I'm still relatively new to Python and have just entered the curious/exploratory phase.

It is my understanding that Python does not support the creating of classes that cannot be subclassed (final classes). However, it seems to me that the bool class in Python cannot be subclassed. This makes sense when the intent of the bool class is considered (because bool is only supposed to have two values: true and false), and I'm happy with that. What I want to know is how this class was marked as final.

So my question is: how exactly did Guido manage to prevent subclassing of 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

Related question: Why I can't extend bool in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simulate the same effect from Python 3.x quite easily:

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

will give the following output:

Traceback (most recent call last):
  File "C:Tempfinal.py", line 10, in <module>
    class D(C): pass
  File "C:Tempfinal.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...