Jeremy Cochoy
Jeremy Cochoy

Reputation: 2652

How to call a private (file scope) function from a class define in the same file

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? (:

Actual example that do not work:

def __private_function():
    pass

class MyClass:
    def my_method(self):
        __private_function()

Error: NameError: name '_MyClass__private_function' is not defined

Nb:

Similar but not a duplicate of Calling private function within the same class python.

Upvotes: 0

Views: 238

Answers (2)

Sheng Zhuang
Sheng Zhuang

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

Alex Hall
Alex Hall

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

Related Questions