0

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.

nck
  • 1,673
  • 16
  • 40
  • Don't begin the function name with double underscore. That has special meaning inside classes. – Barmar Apr 11 '22 at 21:18
  • 1
    See: https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name. This is normally used for "private" _methods_, but IMHO, it's quite strange that the name gets mangled even for global functions... – ForceBru Apr 11 '22 at 21:23

1 Answers1

4

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30