Skip to content Skip to sidebar Skip to footer

Best Way For A Class To Access A Private Method (private Name Mangling)

If I have this: class Test: def __init__(self, x): self.x = x def A(self): __doA() def __doA(): print 'A' if __name__ == '__main__': t = Test(1)

Solution 1:

Here is a short script to recreate the error:

def __foo(x):
    print x

__foo("foo")

class Bar(object):
    def baz(self, x):
        __foo(x)


Bar().baz("foo")

Which results in:

foo # direct call works

Traceback (most recent call last):
  File "C:/Python27/test.py", line 11, in <module>
    Bar().baz("foo")
  File "C:/Python27/test.py", line 8, in baz
    __foo(x)
NameError:global name '_Bar__foo' is not defined # gets mangled in class, breaks

You shouldn't give functions (as distinct from methods) names with leading double underscores, as this breaks name mangling when you try to access them from inside classes - the function becomes unreachable, as there's no class name to mangle onto the front of it.

If you want to indicate a function is private use a single leading underscore, but we're all consenting adults here.

Post a Comment for "Best Way For A Class To Access A Private Method (private Name Mangling)"