0

I'm currently stunned by some Python behavior:

class Base(object):
    def foo(self):
        self.__virtual_function()
        self.virtual_function()
    def __virtual_function(self):
        print("private Base")
    def virtual_function(self):
        print("public Base")

class Derived(Base):
    def __virtual_function(self):
        print("private Derived")
    def virtual_function(self):
        print("public Derived")

d = Derived()
d.foo()

This prints

private Base
public Derived

Is the double underscore effectively making a method private, and thus not overridable by subclasses?

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • Dupe explains it well, there is a name mangling under the hood. – Łukasz Rogalski Jun 09 '17 at 07:55
  • While the double-underscore does effectively make an attribute "private", it wasn't designed to that. See [this talk](https://www.youtube.com/watch?v=HTLu2DFOdTg&t=33m8s) by Raymond Hettinger. Stick around for the discussion of getters/setters and properties, if you are coming from C++. – juanpa.arrivillaga Jun 09 '17 at 08:35
  • @juanpa.arrivillaga it doesn't make anything private, I found out, it rather serves as an identifier for (non-overridable) class methods. – xtofl Jun 09 '17 at 09:25

0 Answers0