2015-05-29 5 views
1

Моя структура папок, как это:питон не может использовать функцию в подмодуль

pythonstuff/ 
    program.py 
    moduleA/ 
     __init__.py 
     foo.py 
     bar.py 

Вот мой код bar.py:

def hello(): 
    print("Hello, world!") 

Вот мой код program.py:

#!/usr/bin/env python3 
from moduleA import bar 
bar.hello() 

Я бегу $ python3 program.py

Как-то я получаю сообщение об ошибке:

File "program.py", line 3, in <module> 
bar.hello() 
AttributeError: 'module' object has no attribute 'hello' 

Edit: мой __init__.py файл пуст.

Edit2: После попытки все, что я наконец понял, у меня был bar.py в корневом каталоге, который фактически содержал метод hello(). bar.py в moduleA/ директория была пуста.

+2

Что находится в вашем файле __init__? – Rcynic

+0

файл инициализации пуст – bvpx

+0

Он работает как expcted для меня под Python 3.4.0 (по умолчанию, 11 апреля 2014, 13:05:11) [GCC 4.8.2] на linux. Проверьте свой PYTHONPATH ??? – msw

ответ

-1

Добавьте это в нее

import os 

__all__ = [] 

for module in os.listdir(os.path.dirname(__file__)): 
    if module != '__init__.py' and module[-3:] == '.py': 
     __all__.append(module[:-3]) 

The init.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the all variable, described later.

из documentation

Так с этим кодом вы явно добавляя модули в ModuleA в всех переменных. This explains the all variable

+0

'__all__' используется для импорта подстановочных знаков. – sobolevn