2017-08-02 113 views
0

例如,我有一個名爲myproject的項目。在myproject目錄中。有other子目錄和main.py。並且在other子目錄中,有a.pyb.py如何組織python的項目結構?

a.py內容是

import b 

main.py內容是:

from other.a import * 

又來了一個問題,在main.py,當我使用from other.a import *a.py的內容包括在main.py,它會引發錯誤,因爲b.pyother,所以在main.py使用import b是錯的,我們應該用import other.b,但是a.py需要import b,所以這是矛盾的。我該如何解決它?

+3

可能重複的[Python項目結構和相對導入](https://stackoverflow.com/questions/34732916/python-project-structure-and-relative-imports) –

+1

@MartinAlonso您鏈接的問題是非常不同這個。 –

+0

您不應該使用包內的相對導入。在Python 3中,它們不起作用,在Python 2中它們已被棄用。所以在'a.py'你需要做'from'。導入b'或'import other.b'。 –

回答

1

我認爲這是你的代碼結構,對嗎?

mypackage 
    other 
     __init__.py 
     a.py # import b 
     b.py # def func_b() 
    __init__.py 
    main.py # from other.a import * 

您可以使用此代碼結構:

請不要在安裝包中使用絕對導入,如:from mypackage.other import bmain.py,使用相對進口如:main.pyfrom .other import b。因爲這樣做,當你有一個腳本test.py

from mypackage import main 

main.b.func_b() 

底層它from .other.a import *

b.func_b(...) 

,因爲你有:

mypackage 
    other 
     __init__.py 
     a.py # from . import b 
     b.py 
    __init__.py 
    main.py # from .other.a import * 

那麼您可以在main.py做到這一點from . import b in a.py。所以*實際上是b,這就是爲什麼你可以使用b.func_b()in main.py