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 "Dive Into Python", which only states a double underscore denotes private functions.

1
  • Step 1: Don't use __ double underscores. Ever. There's no point. Commented Sep 10, 2010 at 1:39

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.