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
这里没有Python关键字-它不是Pythonic。在
一个类是否可以被子类化是由一个名为Py_TPFLAGS_BASETYPE的标志决定的,该标志可以通过C API设置。在
但是,如果您愿意,您可以仅使用Python代码模拟该行为:
Source
在我看来,类一般不应该有任何子类限制。我想建议第三种选择:在你的类文档中添加一个注释,说明这个类不是子类。在
相关问题 更多 >
编程相关推荐