python 如何防止函数在python中被覆盖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2425656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prevent a function from being overridden in python
提问by olamundo
Is there a way to make a class function unoverriddable? something like java's final
keyword. i.e, any overriding class cannot override that method.
有没有办法使类函数不可覆盖?类似于java的final
关键字。即,任何覆盖类都不能覆盖该方法。
回答by Michael Kristofik
You could put a comment in there to the effect of:
你可以在那里发表评论,大意是:
# We'll fire you if you override this method.
It's surprising how well low-tech solutions like this work in practice.
令人惊讶的是,像这样的低技术解决方案在实践中的效果如何。
回答by unholysampler
The issue is you are trying to write in Python using Java philosophies. Some thing carry over, but not all of them. In Python you can do the following and it is perfectly fine, but completely goes against how Java thinks of objects.
问题是您正在尝试使用 Java 哲学用 Python 编写。有些东西会延续,但不是全部。在 Python 中,您可以执行以下操作,这完全没问题,但完全违背 Java 对对象的看法。
class Thing(object):
x = 1
something = Thing()
something.y = something.x
If you really want it, you can try the code posted here. But as you can see there is a lot of code there to get it to do what you want. It also should be noted that even the person that posted the code says it can be by passed using __dict__
or object.__setattr__
.
如果你真的想要它,你可以试试这里发布的代码。但是正如你所看到的,有很多代码可以让它做你想做的事。还应该注意的是,即使是发布代码的人也说它可以使用__dict__
或传递object.__setattr__
。
回答by Paddy3118
Yes there is, don't do it.
是的,不要这样做。
I should add to this after the down-vote. Such protection mechanisms are seen by some to go against the ethos of Python, that "we are all consenting adults here".Who do you want to protect such functions from? And if a comment will not suffice why would something 'stronger'?
我应该在投反对票后补充这一点。有些人认为这样的保护机制违背了 Python 的精神,即“我们在这里都是成年人”。你想保护这些功能免受谁的侵害?如果评论还不够,为什么会有“更强”的东西?
I would document your expectations and expect other programmers to act responsibly.
我会记录您的期望,并希望其他程序员采取负责任的行动。
回答by Arvind Mannem
Using a double underscore before a method in a class is not just a naming convention. By doing so the method name is mangled with classname(_classname__methodname())
.
在类中的方法之前使用双下划线不仅仅是一种命名约定。通过这样做,方法名称被classname(_classname__methodname())
.
By inheriting a class with a method having double underscores in front of it;for the child class it becomes difficult to override the above specified method. This practice is almost equivalent to final in java.
通过继承一个前面有双下划线的方法的类;对于子类,覆盖上面指定的方法变得困难。这种做法几乎相当于java中的final。