开发者

How do you call a private module function from inside a class?

I开发者_Go百科 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜