问题描述
我在 python文档中遇到了以下内容:
I came across the following in the python docs:
使用标准真值测试过程将值转换为布尔值.如果x为false或省略,则返回False;否则为false.否则 返回True. bool也是一个类,它是int的子类. 班级 bool不能再进一步子类化.它的唯一实例是False和 是的.
Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.
我一生中从未想过要继承bool
,但自然而然地,我立即尝试了它,而且很确定:
I've never in my life wanted to subclass bool
, but naturally I immediately tried it, and sure enough:
>>> class Bool(bool):
pass
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
class Bool(bool):
TypeError: Error when calling the metaclass bases
type 'bool' is not an acceptable base type
所以,问题是:这是怎么做的?我是否可以使用相同的技术(或不同的技术)将自己的类标记为final
,即防止它们被子类化?
So, the question: How is this done? And can I apply the same technique (or a different one) to mark my own classes as final
, i.e., to keep them from being subclassed?
推荐答案
bool
类型在C中定义,并且其tp_flags
插槽故意不包含 Py_TPFLAGS_BASETYPE
标志.
The bool
type is defined in C, and its tp_flags
slot deliberately does not include the Py_TPFLAGS_BASETYPE
flag.
C类型需要将自己明确地标记为为可归类的.
C types need to mark themselves explicitly as subclassable.
要对自定义Python类执行此操作,请使用元类:
To do this for custom Python classes, use a metaclass:
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 Foo:
__metaclass__ = Final
class Bar(Foo):
pass
给予:
>>> class Bar(Foo):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __new__
TypeError: type 'Foo' is not an acceptable base type
这篇关于python如何防止类被子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!