[英]How do you call a private module function from inside a class?
I 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.
我在“ Dive Into Python”中使用了两个,但仅指出双下划线表示私有函数。
That is because Python's compiler replaces method calls (and attribute accesses) inside classes if the name begins with two underscores. 这是因为,如果名称以两个下划线开头,则Python的编译器会替换类中的方法调用(和属性访问)。 Seems like this also applies to functions.
似乎这样也适用于函数。 A call to a method
self.__X
would be replaced by self._ClassName__X
, for example. 例如,对方法
self.__X
调用将被self._ClassName__X
代替。 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.
但是在少数情况下这很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.