#file two.py import one print ("top-level in two.py") one.func() if __name__ == "__main__": print ("two.py is being run directly") else: print ("two.py is being imported into another module") '''top-level in one.py one.py is being imported into another module top-level in two.py func() in one.py two.py is being run directly ''' #module one gets loaded,its __name___ equals "one" instead of "__main__"
import one print("TOP LEVEL TWO.PY") one.func() if __name__ == '__main__': print("Two.py being run directly") else: print("two is being imported")
#two.py from one import func func() def func(): print("Func() IN TWO.PY") print('TOP LEVEL IN TWO.PY') if __name__ == '__main__': print('TWO.PY is being run directory !') else: print('TWO.PY has been imported!')
# -*- coding: utf-8 -*- """ Created on Tue Jun 4 14:00:35 2019 @author: Training """ import os os.getcwd() import one as three #from one import func three.func() print(three.var_2) print("Hi")
# latihan 10.name and main.py import one # ini dari one.py print("TOP LEVEL TWO.PY") one.func( ) # mengambil method dari one.py yakni func() maka setelah import one, untuk menggunakan method tersebut/panggil dengan one.func() # jadi akan memanggil seluruh fungsi dari one.py dari method func() #selanjutnya menampilkan argument dari two.py # logic if __name__ == '__main__': print("Two.py being run directly") else: print("two is being imported") #jika one.py di run maka hasilnya: #TOP LEVEL ONE.PY #one.py is being run directly #jika two.py dirun maka hasilnya # TOP LEVEL ONE.PY # one.py has been imported # TOP LEVEL TWO.PY # func() in one.py # Two.py being run directly #kasusnya jika di two.py method one.func() akan membaca file yang terimport sekaligus menjalankan method func() maka dari itu argument #pada one.py if __name__ == '__main__': akan bernilai print("one.py has been imported"), namun jika diakses didalam methodnya sendiri atau file name sendiri maka dia akan bersifat directly
import one print( one.func() ) print('top-level in two.py')
# file two.py import one as o print("top-level in two.py") o.func() def func(): print("func() in two.py") if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module") func()