說我有兩個Python模塊:Python的禮儀:導入模塊
module1.py
:
import module2
def myFunct(): print "called from module1"
module2.py
:
def myFunct(): print "called from module2"
def someFunct(): print "also called from module2"
如果我輸入module1
,豈不是更好禮儀重新導入module2
,或只是將其稱爲module1.module2
?
例如(someotherfile.py
):
import module1
module1.myFunct() # prints "called from module1"
module1.module2.myFunct() # prints "called from module2"
我也可以這樣做:module2 = module1.module2
。現在,我可以直接撥打module2.myFunct()
。
不過,我可以改變module1.py
到:也
import module1
module1.myFunct() # prints "called from module1"; overrides module2
module1.someFunct() # prints "also called from module2"
,通過導入*
,幫助( '模塊1')顯示所有:
from module2 import *
def myFunct(): print "called from module1"
現在,在someotherfile.py
,我能做到這一點來自module2
的功能。
在另一方面,(假設module1.py
使用import module2
),我可以這樣做: someotherfile.py
:
import module1, module2
module1.myFunct() # prints "called from module1"
module2.myFunct() # prints "called from module2"
再次,這是更好的禮儀和實踐?要再次輸入module2
,還是隻想參考module1
的輸入?