Reputation: 2652
In one file I define a class and a private function. I want to call this function within a method. What is the syntax to reference the "outerscope" of the class and tell python where my function lives? (:
def __private_function():
pass
class MyClass:
def my_method(self):
__private_function()
Error: NameError: name '_MyClass__private_function' is not defined
Similar but not a duplicate of Calling private function within the same class python.
Upvotes: 0
Views: 238
Reputation: 697
Use single underscore to avoid name mangling.
def _private_function():
print('use single underscore to avoid name mangling.')
class MyClass:
def my_method(self):
_private_function()
a = MyClass()
a.my_method()
Upvotes: 2
Reputation: 36063
This works:
globals()['__private_function']()
But if you can, just don't name the function with two underscores. I don't think there's any good reason outside of a class.
Upvotes: 1