A module is a file that contains Python definitions and statements.
(The suffix of the file name is .py
)
The following files can also be handled as modules.
HelloWorld.py
print( “HelloWorld” )
As an example, import the ʻos` module of the standard library.
import_test.py
import os
print( type( os ) )
# <class ‘module’>
print( os.getcwd() )
# /private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/Test
As mentioned above, you can import by doing ʻimport . Modules are imported as objects of type
module`.
directory
- iCould - Test - MyFunc - MyCalc.py - MyCalcTest.py
We will proceed with the above directories.
Import the MyCalc.py
module with MyCalcTest.py
Try using the functions in the MyCalc.py
module.
MyCalc.py
'''
Self-made calculation module
'''
def sum ( v1, v2 ) :
'''
Addition
'''
return v1 + v2
def sub ( v1, v2 ) :
'''
Subtraction
'''
return v1 - v2
MyCalcTest.py
import MyFunc.MyCalc
v1 = 10
v2 = 5
res1 = MyFunc.MyCalc.add( v1, v2 )
print( "%d + %d = %d" %( v1, v2, res1 ) )
#>> 10 + 5 = 15
res2 = MyFunc.MyCalc.sub( v1, v2 )
print( "%d - %d = %d" %( v1, v2, res2 ) )
# 10 - 5 = 5
I was able to use the functions of the MyCalc.py
module like this.
It's a hassle to write MyFunc.MyCalc.add
every time.
You can import an object with from <module name> import <object name>
.
import_test.py
from MyFunc.MyCalc import add, sub
v1 = 10
v2 = 5
res1 = add( v1, v2 )
print( "%d + %d = %d" %( v1, v2, res1 ) )
res2 = sub( v1, v2 )
print( "%d - %d = %d" %( v1, v2, res2 ) )
All objects can be imported using the wildcard *
.
import_test.py
from MyFunc.MyCalc import *
v1 = 10
v2 = 5
res1 = add( v1, v2 )
print( "%d + %d = %d" %( v1, v2, res1 ) )
res2 = sub( v1, v2 )
print( "%d - %d = %d" %( v1, v2, res2 ) )
Depending on the directory hierarchy, the imported path name may be long. It is better to specify the object instead of using it as it is. Does wildcard exist in the namespace to be very easy to use? It may be better to refrain from it because it is unknown.
Recommended Posts