Python相当于.Net的密封类 [英] Python's equivalent of .Net's sealed class

查看:175
本文介绍了Python相当于.Net的密封类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python是否有与密封类相似的东西?我相信它在Java中也被称为最终类。

Does python have anything similar to a sealed class? I believe it's also known as final class, in java.

换句话说,在python中,我们可以标记一个类,使其永远不能被继承或扩展吗? python是否曾经考虑过具有这种功能?为什么?

In other words, in python, can we mark a class so it can never be inherited or expanded upon? Did python ever considered having such a feature? Why?


实际上试图理解,为什么?// stackoverflow.com/questions/554894/why-does-the-sealed-keyword-exist-in-net> 在此处回答(以及很多许多许多很多很多很多地方)一点都不让我满意,所以我试图从另一个角度看。请避免对此问题的理论答案,而要注意标题!或者,如果您坚持要求,至少请举一个一个非常好且实用的csharp密封类示例,指出如果不密封将破坏大量时间。

Actually trying to understand why sealed classes even exist. Answer here (and in many, many, many, many, many, really many other places) did not satisfy me at all, so I'm trying to look from a different angle. Please, avoid theoretical answers to this question, and focus on the title! Or, if you'd insist, at least please give one very good and practical example of a sealed class in csharp, pointing what would break big time if it was unsealed.


我都不是这两种语言的专家,但我确实对这两种语言都有一点了解。就在昨天,在使用csharp进行编码时,我了解了密封类的存在。现在我想知道python是否具有与此等效的功能。我相信存在它的理由非常充分,但是我真的不明白。

推荐答案

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

You can use a metaclass to prevent subclassing:

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__ =最终行使 Foo 类封闭

请注意,您将在.NET中使用密封类作为性能指标;因为不会有任何子类化方法可以直接解决。 Python方法查找的工作方式大不相同,就方法查找而言,使用像上面的示例这样的元类没有好处或缺点。

Note that you'd use a sealed class in .NET as a performance measure; since there won't be any subclassing methods can be addressed directly. Python method lookups work very differently, and there is no advantage or disadvantage, when it comes to method lookups, to using a metaclass like the above example.

这篇关于Python相当于.Net的密封类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆