How to prevent a function from being overridden in

2019-01-25 01:35发布

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.

4条回答
劫难
2楼-- · 2019-01-25 02:17

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-25 02:25

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.

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__.

查看更多
爷的心禁止访问
4楼-- · 2019-01-25 02:26

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()).

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.

查看更多
女痞
5楼-- · 2019-01-25 02:34

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'?

I would document your expectations and expect other programmers to act responsibly.

查看更多
登录 后发表回答