Calling Private Function Within The Same Class Python
Answer :
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.
__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.
Comments
Post a Comment