简体   繁体   English

您如何从类内部调用私有模块函数?

[英]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.

相关问题 你如何从一个类的另一个实例调用一个类的函数? - How do you call a function of a class from another instance of a class? 你怎么知道你导入的模块是函数还是类? - How do you know that module you are importing is function or class? 在将类分配给变量和函数内部时,如何调用类的方法? - How do you call a class's method when it is assigned to a variable and inside a function? 你如何在一个类中的另一个函数中使用一个函数? - How do you use a function in a class, inside another function? 如何从 class 外部调用 class 内部的 function? - How do i call a function that's inside a class from outside of the class? 如何在 class 定义中调用 class function ? - How do I call a class function inside the class definition? 如何在不同类中的函数中更改变量并进行回调? - How do you change the variable in a function from a different class and call it back? 如何在Python中将对类/函数的调用转换为字符串? - How do you convert a call to a class/function to a string in Python? Python:如何从类中的函数调用特定变量? - Python: How do I call a specific variable from a function inside the class? 如何从另一个类内部的函数中调用一个类? - How to call a class from a function which is inside another class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM