[Python-ideas] The prohibition overrides the class method

Random832 random832 at fastmail.com
Mon Nov 16 18:39:27 EST 2015


I'm not sure how this thread has gone on this long without anyone
mentioning __methods.

If you prefix a method with two underscores, it will transform the name
of the method in order to make it difficult to accidentally override.

So in other methods inside the base class that need to call your method,
you can call the underscored version and subclasses won't override it (I
think it's possible for them to 

e.g.

class A:
    def __test(self):
        print("123")
    def test(self):
        return self.__internal_test()
    def other_function(self):
        ...
        self.__test()
        ...


class B(A):
    def __test(self):
        print("456")


>>> B().test()
123


B can still override test if it wants to, but it won't affect any calls
to the __test method from A's other methods. If it *really* wants to, it
can override _A__test(), but someone's not likely to do that by mistake.



More information about the Python-ideas mailing list