問題描述
我對 Python 完全陌生,我知道這個問題被問過很多次,但不幸的是,我的情況似乎有點不同......我已經創建了一個包(或者我認為).目錄樹是這樣的:
I'm totally new to Python and I know this question was asked many times, but unfortunately it seems that my situation is a bit different... I have created a package (or so I think). The catalog tree is like this:
mydir
lib (__init__.py)
mod1 (__init__.py, mod11.py)
括號中是目錄中的文件.兩個 __init__.py
文件都是零長度.
In parenthesis there are files in the catalog. Both __init__.py
files are zero length.
文件 mydir/lib/mod1/mod11.py
包含以下內容:
The file mydir/lib/mod1/mod11.py
contains the following:
def mod12():
print "mod12"
現在,我運行 python
,然后運行 ??import lib
,運行正常,然后運行 ??lib.mod11()
或 lib.mod12()
.
Now, I run python
, then import lib
, which works OK, then lib.mod11()
or lib.mod12()
.
最后兩個中的任何一個都給了我主題錯誤消息.實際上,步驟 2 之后的 dir(lib)
也不顯示 mod11
或 mod12
.看來我錯過了一些非常簡單的東西.
Either of the last two gives me the subject error message. Actually dir(lib)
after Step 2 does not display mod11
or mod12
either.
It seems I'm missing something really simple.
(我在 Ubuntu 10.10 中使用 Python 2.6)
(I'm using Python 2.6 in Ubuntu 10.10)
謝謝
推薦答案
當你 import lib
時,你正在導入包.在這種情況下,唯一要評估和運行的文件是 lib 目錄中的 0 字節 __init__.py
.
When you import lib
, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py
in the lib directory.
如果你想訪問你的函數,你可以執行類似 from lib.mod1 import mod1
的操作,然后像 mod1 那樣運行
.mod12
函數.mod12()
If you want access to your function, you can do something like this from lib.mod1 import mod1
and then run the mod12
function like so mod1.mod12()
.
如果你想在導入lib
的時候能夠訪問mod1
,你需要在里面放一個
文件.import mod1
lib
目錄中的 __init__.py
If you want to be able to access mod1
when you import lib
, you need to put an import mod1
inside the __init__.py
file inside the lib
directory.
這篇關于Python 錯誤:AttributeError:“模塊"對象沒有屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!