Python 3.x中的最后一课 - Guido没有告诉我什么? [英] Final classes in Python 3.x- something Guido isn't telling me?
问题描述
这个问题建立在许多假设之上。如果一个假设是错误的,那么整个事情就会失败。我还是相对较新的Python,刚刚进入了好奇/探索阶段。
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.
我的理解是Python不支持创建无法子类化的类(最终类)。但是,在我看来,Python中的 bool 类不能被子类化。当考虑bool类的意图时,这是有道理的(因为bool只应该有两个值:true和false),我很满意。我想知道的是如何这个类被标记为最终。
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.
所以我的问题是:究竟是怎么回事Guido是否设法阻止bool的子类化?
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
相关问题: 为什么我可以在Python中扩展bool?
推荐答案
您可以非常轻松地模拟Python 3.x中的相同效果:
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
将提供以下输出:
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
这篇关于Python 3.x中的最后一课 - Guido没有告诉我什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!