如何在Python中导入私有方法?

Use*_*007 4 python

def __hello_world(*args, **kwargs):
  .....
Run Code Online (Sandbox Code Playgroud)

我试过

from myfile import __helloworld
Run Code Online (Sandbox Code Playgroud)

我可以导入非私人的.

如何导入私有方法?

谢谢.


我现在使用单个下划线.

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    from myfile.ext import _hello_world
ImportError: cannot import name _hello_world
Run Code Online (Sandbox Code Playgroud)

在我的test.py中

sys.path.insert(0, os.path.abspath(
                    os.path.join(
                        os.path.dirname(__file__), os.path.pardir)))

from myfile.ext import _hello_world
Run Code Online (Sandbox Code Playgroud)

Amb*_*ber 7

$ cat foo.py
def __bar():
    pass
Run Code Online (Sandbox Code Playgroud)
$ cat bar.py
from foo import __bar

print repr(__bar)
Run Code Online (Sandbox Code Playgroud)
$ python bar.py
<function __bar at 0x14cf6e0>
Run Code Online (Sandbox Code Playgroud)

也许你弄错了?

但是,通常双下划线方法通常不是必需的 - 通常"公共"API是零下划线,而"私有"API是单下划线.

  • 通常这就是使用单下划线方法. (2认同)