在同一个类python中调用私有函数

bad*_*ash 29 python private function call

如何从同一个类中的其他函数调用私有函数?

class Foo:
  def __bar(arg):
    #do something
  def baz(self, arg):
    #want to call __bar
Run Code Online (Sandbox Code Playgroud)

现在,当我这样做时:

__bar(val)
Run Code Online (Sandbox Code Playgroud)

从baz(),我得到这个:

NameError: global name '_Foo__createCodeBehind' is not defined
Run Code Online (Sandbox Code Playgroud)

有人能告诉我错误的原因是什么吗?另外,我如何从另一个私人函数调用私有函数?

Rob*_*ers 40

this->Python中没有像C/C++等那样隐式.你必须调用它self.

class Foo:
     def __bar(self, arg):
         #do something
     def baz(self, arg):
         self.__bar(arg)
Run Code Online (Sandbox Code Playgroud)

但这些方法并不是真正私密的.当您使用两个下划线启动一个方法名称时,Python会对其进行一些名称修改以使其"私有",而这就是它所做的一切,它不像其他语言那样强制执行任何操作.如果您定义__baron Foo,它仍然可以从对象外部访问Foo._Foo__bar.例如,人们可以这样做:

f = Foo()
f._Foo__bar('a')
Run Code Online (Sandbox Code Playgroud)

这解释了您收到的错误消息中的"奇数"标识符.

您可以here在文档中找到它.


sen*_*rle 7

__bar是"私人的"(在某种意义上它的名称已被破坏),但它仍然是一种方法Foo,所以你必须通过它来引用它self并传递self给它.只是用裸电话打电话是__bar()行不通的; 你必须像这样称呼:self.__bar().所以...

>>> class Foo(object):
...   def __bar(self, arg):
...     print '__bar called with arg ' + arg
...   def baz(self, arg):
...     self.__bar(arg)
... 
>>> f = Foo()
>>> f.baz('a')
__bar called with arg a
Run Code Online (Sandbox Code Playgroud)

您可以self.__barFoo定义中的任何位置访问,但是一旦超出定义,就必须使用foo_object._Foo__bar().这有助于避免类继承上下文中的命名空间冲突.如果这不是您使用此功能的原因,那么您可能错误地使用了它.