python - python如何防止类被子类化?

标签 python subclass final

<分区>

我在 python docs 中遇到了以下内容:

bool([x])

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,但我自然而然地立即尝试了一下,果然如此:

>>> 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,即防止它们被子类化?

最佳答案

bool 类型是在 C 中定义的,它的 tp_flags 槽故意不包括 Py_TPFLAGS_BASETYPE flag .

C 类型需要将自己明确标记为可子类。

要为自定义 Python 类执行此操作,请使用元类:

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 - python如何防止类被子类化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16056574/

相关文章:

python - Whoosh NestedChildren 搜索未返回所有结果

objective-c - (Objective-C/Cocoa) Casted Superclass 保持不变

actionscript-3 - 为什么不能使用 "final"是一个安全问题?

java - 添加标签的最终 JPanel (java)

python - MPI 分散分布大型 csv 文件

python - 使用 python 在 Azure Functions 中进行路由

java - 创建与子类相同类型的对象

java - 为什么私有(private)方法也不能是最终的?

python - 如何在 PySpark 中使用窗口函数?

java - 父类初始化时创建子类对象