在同一个类中调用私有函数python
如何从同一类中的其他函数调用私有函数?
class Foo:
def __bar(arg):
#do something
def baz(self, arg):
#want to call __bar
现在,当我这样做时:
__bar(val)
从 baz() 中,我得到这个:
NameError: global name '_Foo__createCodeBehind' is not defined
有人能告诉我错误的原因是什么吗? 另外,如何从另一个私有函数调用私有函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 中没有像 C/C++ 等中那样的隐式
this->
。您必须在self
上调用它。但这些方法并不是真正私有的。当你以两个下划线开头的方法名称时,Python 会进行一些名称修改以使其成为“私有”,这就是它所做的一切,它不会像其他语言那样强制执行任何操作。如果您在
Foo
上定义__bar
,仍然可以通过Foo._Foo__bar
从对象外部访问它。例如,可以这样做:这也解释了您收到的错误消息中的“奇数”标识符。
您可以在文档中
此处
找到它。There is no implicit
this->
in Python like you have in C/C++ etc. You have to call it onself
.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
onFoo
, it is still accesible from outside of the object throughFoo._Foo__bar
. E.g., one can do this:This explains the "odd" identifier in the error message you got as well.
You can find it
here
in the docs.__bar
是“私有”(从某种意义上说,它的名称是 mangled),但它仍然是Foo
的方法,因此您必须通过self
引用它并将self
传递给它。仅仅用一个空的__bar()
来调用它是行不通的;你必须像这样调用它:self.__bar()
。所以...您可以在
Foo
定义中的任何位置访问self.__bar
,但是一旦超出定义,您就必须使用foo_object._Foo__bar( )
。这有助于避免类继承上下文中的名称空间冲突。如果这不是您使用此功能的原因,您可能会重新考虑使用它。在 Python 中创建“私有”变量和方法的约定是在名称前添加下划线。这没有语法意义,但它向代码的用户传达了变量或方法是可能更改的实现细节的一部分。
__bar
is "private" (in the sense that its name has been mangled), but it's still a method ofFoo
, so you have to reference it viaself
and passself
to it. Just calling it with a bare__bar()
won't work; you have to call it like so:self.__bar()
. So...You can access
self.__bar
anywhere within yourFoo
definition, but once you're outside the definition, you have to usefoo_object._Foo__bar()
. This helps avoid namespace collisions in the context of class inheritance.If that's not why you're using this feature, you might reconsider using it. The convention for creating "private" variables and methods in Python is to prepend an underscore to the name. This has no syntactic significance, but it conveys to users of your code that the variable or method is part of implementation details that may change.