Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a function from being overridden in python [duplicate]

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.

like image 563
olamundo Avatar asked Mar 11 '10 14:03

olamundo


People also ask

How do you stop a function from being overridden in Python?

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.

How do you stop overwrite names in Python?

You can't prevent it, Python is built on the notion of "we're all consenting adults" so you are free to do what you want. It is possible to delete the override but you'd have to know that you shadowed that function in the first place.

Can you overwrite functions in Python?

Method overriding in Python is when you have two methods with the same name that each perform different tasks. This is an important feature of inheritance in Python. In method overriding, the child class can change its functions that are defined by its ancestral classes.


2 Answers

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.

like image 143
Michael Kristofik Avatar answered Sep 26 '22 20:09

Michael Kristofik


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

like image 21
unholysampler Avatar answered Sep 22 '22 20:09

unholysampler