Calling private function within the same class python

badmaash picture badmaash · Feb 5, 2012 · Viewed 50.1k times · Source

How can i call a private function from some other function within the same class?

class Foo:
  def __bar(arg):
    #do something
  def baz(self, arg):
    #want to call __bar

Right now, when i do this:

__bar(val)

from baz(), i get this:

NameError: global name '_Foo__createCodeBehind' is not defined

Can someone tell me what the reason of the error is? Also, how can i call a private function from another private function?

Answer

Rob Wouters picture Rob Wouters · Feb 5, 2012

There is no implicit this-> in Python like you have in C/C++ etc. You have to call it on self.

class Foo:
     def __bar(self, arg):
         #do something
     def baz(self, arg):
         self.__bar(arg)

These methods are not really private though. When you start a method name with two underscores Python does some name mangling to make it "private" and that's all it does, it does not enforce anything like other languages do. If you define __bar on Foo, it is still accesible from outside of the object through Foo._Foo__bar. E.g., one can do this:

f = Foo()
f._Foo__bar('a')

This explains the "odd" identifier in the error message you got as well.

You can find it here in the docs.