Skip to main content
 首页 » 编程设计

Python 导入问题,找不到模块

2025年05月04日13me-sa

来 self 在 https://docs.python.org/2/tutorial/modules.html 上阅读的所有内容,main.py 代码应该可以工作。我一辈子都弄不明白为什么它不起作用。

版本等

vagrant@vagrant-ubuntu-precise-64:/vagrant/monkey$ python --version 
Python 2.7.3 

目录结构

vagrant@vagrant-ubuntu-precise-64:/vagrant/monkey$ ll 
total 6 
drwxrwxrwx 1 vagrant vagrant    0 Jul 30 07:18 ./ 
drwxrwxrwx 1 vagrant vagrant 4096 Jul 30 07:04 ../ 
-rwxrwxrwx 1 vagrant vagrant   76 Jul 30 07:09 abc.py* 
-rwxrwxrwx 1 vagrant vagrant   76 Jul 30 07:10 bcd.py* 
-rwxrwxrwx 1 vagrant vagrant   43 Jul 30 06:56 main.py* 

abc.py

# abc module 
 
 
def bar(): 
    print 'abc.bar called.' 
    return None 

bcd.py

# bcd module 
 
 
def foo(): 
    print 'bcd.foo called.' 
    return None 

主.py

import abc 
import bcd 
 
 
abc.bar() 
bcd.foo() 

错误

vagrant@vagrant-ubuntu-precise-64:/vagrant/monkey$ python main.py 
Traceback (most recent call last): 
  File "main.py", line 5, in <module> 
    abc.bar() 
AttributeError: 'module' object has no attribute 'bar' 

请您参考如下方法:

abc is a builtin Python module .将您的 abc.py 重命名为其他名称。