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?
In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with double underscore “__”.
Within the same class public and private will make no difference to you.
To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.
In python programming, there are no private methods that cannot be accessed except inside the class. To define the private method, you have to prefix the member name with a double underscore(__).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With