Nói rằng tôi có hai mô-đun Python:Python Phong tục: Nhập khẩu Modules
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"
Nếu tôi nhập module1
, nó là nghi thức tốt hơn để tái nhập khẩu module2
hoặc chỉ gọi nó là module1.module2
?
Ví dụ (someotherfile.py
):
import module1
module1.myFunct() # prints "called from module1"
module1.module2.myFunct() # prints "called from module2"
tôi cũng có thể làm điều này: module2 = module1.module2
. Bây giờ, tôi có thể gọi trực tiếp module2.myFunct()
.
Tuy nhiên, tôi có thể thay đổi module1.py
tới:
from module2 import *
def myFunct(): print "called from module1"
Bây giờ, trong someotherfile.py
, tôi có thể làm điều này:
import module1
module1.myFunct() # prints "called from module1"; overrides module2
module1.someFunct() # prints "also called from module2"
Ngoài ra, bằng cách nhập *
, giúp đỡ ('module1') cho thấy tất cả của các hàm từ module2
.
Mặt khác, (giả sử module1.py
sử dụng import module2
), tôi có thể làm: someotherfile.py
:
import module1, module2
module1.myFunct() # prints "called from module1"
module2.myFunct() # prints "called from module2"
Một lần nữa, đó là nghi thức tốt hơn và thực hành? Để nhập lại module2
hoặc chỉ để tham chiếu nhập module1
?