首页 > 解决方案 > 从另一个文件调用 __init__.py

问题描述

我试图了解 __init__py 是如何工作的。但我有以下问题。

我有以下目录:

myfoldername/
   example/
      __init__.py
      sayhello.py
      saybye.py
   main.py

在 __init__py 文件中,我导入 sayhello.py 和 saybye.py 文件

from example.sayhello import *
from example.saybye import *

在 sayhello.py 里面我有两个函数:

def hello():
    print('hello')

def hello_person(x):
    print('hello ' + x)

为什么在将模块导入单独的脚本 main.py 时不能调用 sayhello.py 中的两个函数?

import example as ex

ex.hello() //prints 'hello'

ex.hello_person('John')  //prints module 'example' has no attribute 'hello_person'

标签: pythonpython-3.x

解决方案


虽然那不应该发生。但如果问题仍然存在,您可以使用The Zen of Python。哪个说

显式优于隐式。

因此,

from example.sayhello import hello, hello_person

推荐阅读