views:

219

answers:

3

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.

+8  A: 

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

unholysampler
-1 Such code deserves the Maginot Memorial Prize For Futile Defence Mechanisms.
John Machin
Why the -1? I didn't write the code I linked to and I didn't encourage it's use. I found it with a google search and thought it helped prove my point that trying to enforce final is not a good idea in python.
unholysampler
For even linking to it.
John Machin
+8  A: 

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.

Kristo
+1 And if this was discovered from a user bug report, we'll fire the wallies who didn't test the app properly.
John Machin
This should be part of the doc strings (i.e. API spec) rather than a comment
vog
A: 

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.

  • Paddy.
Paddy3118