__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.