""" Imports practice Make a directory with 2 modules; make a function in one of them; then import this function in the other module and use that in your script of choice. """ from module2 import hello if __name__ == "__main__": print(hello())
""" The sys module. The “sys.path” list is initialized from the PYTHONPATH environment variable. Is it possible to change it from within Python? If so, does it affect where Python looks for module files? Run some interactive tests to find it out. """ import sys if __name__ == "__main__": print(sys.path) sys.path.insert(0, '../task_1') print(sys.path) import module2 print(module2.hello())
import sys import importer module1 = importer.import_('module1', 'module1_source.py', '.') print('sys say:', sys.modules.get('module1', 'module1 not found')) import module2 module2.hello()
import module2 module2.hello(__name__)
""" def add(*num): result=1 for i in num: result+=i return result print(add()) print(add(1)) print(add(1,2,3,4)) """ import module1 as m1 import module2 as m2 import module3 as m3 m1.care() m2.hello() m3.bar() #////////def練習///////// """ def gcd(x,y): if x>y: x,y=y,x for factor in range(x,1,-1): if x%factor==0 and y%factor==0: return factor def lcm(x,y): return x*y//gcd(x,y) print(gcd(15,27)) print(lcm(15,27)) """
import sys import importer #it will print Running importer.py module1 = importer.import_('module1','module1_source.py','.') #it will import modules from module1_source.py in the same directory(cuz '.') print(globals()) #this will contain module1 in the globals() dictiionary module1.hello() import module2 module2.hello() #if we run this hello function it won't print importing module1.py as module1 is imported only once and then it is registered in sys.modules hence when module1.hello is called in module2, it won't import it again and then just run the hello function in module1