在Python中,我该如何禁止类继承?

2024-05-13 19:24:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在看一个演讲(How to design a good API and why it matters),其中有一句话,字面意思是“设计和文档继承,否则禁止继承”。演讲以Java为例,其中有一个“final”关键字来禁止子类化。在Python中可以禁止子类化吗?如果是的,很高兴看到一个例子。。。 谢谢。在


Tags: toinapisomethingclasseshowfinalme
2条回答

这里没有Python关键字-它不是Pythonic。在

一个类是否可以被子类化是由一个名为Py_TPFLAGS_BASETYPE的标志决定的,该标志可以通过C API设置。在

This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a “final” class in Java).

但是,如果您愿意,您可以仅使用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 C(metaclass=Final): pass

class D(C): pass

Source

在我看来,类一般不应该有任何子类限制。我想建议第三种选择:在你的类文档中添加一个注释,说明这个类不是子类。在

相关问题 更多 >