Python相当于.Net的密封类

cre*_*gox 8 .net python class sealed

python是否有类似于密封类的东西?我相信它在java中也被称为final类.

换句话说,在python中,我们可以标记一个类,以便它永远不会被继承或扩展吗?python曾经考虑过有这样的功能吗?为什么?

免责声明

实际上试图理解为什么密封课程甚至存在.答案在这里(和很多,很多,很多,很多,很多,真的很多其他地方)没有满足我的人,所以我试图从不同的角度看.请避免对这个问题的理论答案,并专注于标题!或者,如果你坚持,至少请给出csharp中密封类的一个非常好的实用例子,指出如果它是未密封的话会破坏大的时间.

我不是两种语言的专家,但我确实知道两种语言.就在昨天,在使用csharp进行编码时,我了解了密封类的存在.现在我想知道python是否有相同的东西.我相信它的存在是有充分理由的,但我真的没有得到它.

Mar*_*ers 12

您可以使用元类来阻止子类化:

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
Run Code Online (Sandbox Code Playgroud)

得到:

>>> 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
Run Code Online (Sandbox Code Playgroud)

__metaclass__ = Final行使Foo该类"密封".

请注意,您在.NET中使用密封类作为性能度量; 因为不会有任何子类化方法可以直接解决.Python方法查找的工作方式非常不同,在方法查找方面,使用类似于上面示例的元类没有任何优点或缺点.