python有没有类似sealed class的东西?我相信它在 Java 中也被称为最终类。
换句话说,在 python 中,我们是否可以标记一个类,使其永远不能被继承或扩展? python有没有考虑过这样的功能?为什么?
免责声明
<支持> 其实是想了解why sealed classes甚至存在。 Answer here (还有 many , many , many , many , many , really many 其他地方)一点都不让我满意,所以我想换个角度看。请避免对这个问题进行理论上的回答,并专注于标题!或者,如果您坚持,至少请给出一个 csharp 中密封类的非常好的和实用的示例,指出如果未密封会破坏什么。
<支持> 我对这两种语言都不是专家,但我确实对两者都有所了解。就在昨天,在 csharp 上编码时,我了解到密封类的存在。现在我想知道 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
__metaclass__ = Final
行使 Foo
类“密封”。
请注意,您将在 .NET 中使用密封类作为性能度量;因为不会有任何子类方法可以直接处理。 Python 方法查找的工作方式截然不同,就方法查找而言,使用如上例所示的元类没有优势或劣势。
关于Python 相当于.Net 的密封类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16564198/