Search code examples
pythonfunctionclasscallprivate

python class fail to provide _Secretive__xxx() function, why?


I was trying to see if I can call a private function of a python class, I tried in ipython:

In [14]: class C:
   ....:     def __my(s):
   ....:         print "hello"
   ....:       

In [15]: print C
__main__.C

In [16]: obj=C()

In [17]: obj._Secretive__my
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-c68d82fedeb4> in <module>()
----> 1 obj._Secretive__my

AttributeError: C instance has no attribute '_Secretive__my'
In [18]: obj._Secretive__my()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-ab4a9965f82a> in <module>()
----> 1 obj._Secretive__my()

Well, seems I cannot stat it or call it, right? Where did I get wrong?


Solution

  • The way you implement “Private” instance variable called name mangling. See doc Private Variables and Class-local References

    ... such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

    Try this:

    obj._C__my
    obj._C__my()