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

前端 未结 1 1676
北荒
北荒 2021-01-15 22:22

I have a module that looks something like this:

def __myFunc():
    ...

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


        
1条回答
  •  梦毁少年i
    2021-01-15 22:40

    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 讨论(0)
提交回复
热议问题