tags:

views:

32

answers:

1

I have a module that looks something like this:

def __myFunc():
    ...

class MyClass(object):
    def __init__(self):
        self.myVar = __myFunc()

and I get the error:

NameError: global name '_MyClass__myFunc' is not defined

How can I call this function from inside the class?

edit: Since posting this, I've discovered I can avoid the automatic mangling by using a single underscore instead of double underscores. I was using two as per http://diveintopython.org/object_oriented_framework/private_functions.html, which only states a double underscore denotes private functions.

+3  A: 

That is because Python's compiler replaces method calls (and attribute accesses) inside classes if the name begins with two underscores. Seems like this also applies to functions. A call to a method self.__X would be replaced by self._ClassName__X, for example. This makes it possible to have pseudo-private attributes and methods.

There is absolutely no reason to use two underscores for functions inside the module. Programmers often follow the convention of putting one underscore in front of the function name if the function shouldn't be called from outside.

Using two underscores is only necessary for attributes/methods in classes if you don't want them to be overwritten by subclasses, for example. But there are few cases in which that is useful.

AndiDog
"But there are few cases in which that is useful". As a practical matter, there are zero cases in which this is useful.
S.Lott