Calling private function within the same class python

Question:

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?

Asked By: badmaash

||

Answers:

__bar is “private” (in the sense that its name has been mangled), but it’s still a method of Foo, so you have to reference it via self and pass self to it. Just calling it with a bare __bar() won’t work; you have to call it like so: self.__bar(). So…

>>> class Foo(object):
...   def __bar(self, arg):
...     print '__bar called with arg ' + arg
...   def baz(self, arg):
...     self.__bar(arg)
... 
>>> f = Foo()
>>> f.baz('a')
__bar called with arg a

You can access self.__bar anywhere within your Foo definition, but once you’re outside the definition, you have to use foo_object._Foo__bar(). This helps avoid namespace collisions in the context of class inheritance.

If that’s not why you’re using this feature, you might reconsider using it. The convention for creating “private” variables and methods in Python is to prepend an underscore to the name. This has no syntactic significance, but it conveys to users of your code that the variable or method is part of implementation details that may change.

Answered By: senderle

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.

Answered By: Rob Wouters
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.