'How can I use a function declared before a class, inside that class in in python 3?

I have this really simple scenario where I want to use one function in multiple classes. So I declare it before the class and then I try to use.

def __ext_function(x):
    print(f'Test{x}')
    
class MyClass():
    some_value: int

    def __init__(self, some_value):
        self.some_value = some_value
        __ext_function(1)

a = MyClass(some_value=1)

But for some reason it keeps telling me that it does not exit:

NameError: name '_MyClass__ext_function' is not defined

I have seen other questions with solutions like this:

def __ext_function(x):
    print(f'Test {x}')
    
class MyClass():
    some_value: int
    ext_func = staticmethod(__ext_function)
    def __init__(self, some_value):
        self.some_value = some_value
        self.ext_func(1)

a = MyClass(some_value=1)

But none seems to work.



Solution 1:[1]

This is a case where Python's usually pure syntax fails. Symbols that start with two underscores get treated specially in a class. If you change that function name to _ext_function, it will work exactly as you expect.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Roberts