在同一个类python中调用私有函数 [英] Calling private function within the same class python

查看:578
本文介绍了在同一个类python中调用私有函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Foo:
如何从同一个类中的其他函数调用私有函数? def __bar(arg):
#do something
def baz(self,arg):
#将会调用__bar

现在,当我这样做时:

  __ bar(val)
$ / code>

from baz(),我得到这个:



< pre $ NameError:全局名称'_Foo__createCodeBehind'未定义

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

解决方案

没有隐含的<$ c Python中的$ c> this-> ,就像你在C / C ++等中一样。你必须在 self 中调用它。

  class Foo:
def __bar(self,arg):
#do something
def baz(self ,arg):
self .__ bar(arg)






这些方法虽然不是真的私人的。当你用两个下划线开始一个方法名时,Python做了一些名字来使它变成私有,这就是它所做的一切,它不像其他语言那样执行任何操作。如果你在 Foo 上定义 __ bar ,它仍然可以通过 Foo从对象外访问._Foo__bar 。例如,可以这样做:

  f = Foo()
f._Foo__bar('a')

这解释了错误消息中的odd标识符。



您可以在这里找到 > 在文档中。


How can i call a private function from some other function within the same class?

class Foo:
  def __bar(arg):
    #do something
  def baz(self, arg):
    #want to call __bar

Right now, when i do this:

__bar(val)

from baz(), i get this:

NameError: global name '_Foo__createCodeBehind' is not defined

Can someone tell me what the reason of the error is? Also, how can i call a private function from another private function?

解决方案

There is no implicit this-> in Python like you have in C/C++ etc. You have to call it on self.

class Foo:
     def __bar(self, arg):
         #do something
     def baz(self, arg):
         self.__bar(arg)


These methods are not really private though. When you start a method name with two underscores Python does some name mangling to make it "private" and that's all it does, it does not enforce anything like other languages do. If you define __bar on Foo, it is still accesible from outside of the object through Foo._Foo__bar. E.g., one can do this:

f = Foo()
f._Foo__bar('a')

This explains the "odd" identifier in the error message you got as well.

You can find it here in the docs.

这篇关于在同一个类python中调用私有函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆